#include <iostream>
#include <sstream>
class Vector
{
double _x;
double _y;
public:
Vector(double x, double y) : _x(x), _y(y) {}
double getX() { return _x; }
double getY() { return _y; }
operator const char*()
{
std::ostringstream os;
os << "Vector(" << getX() << "," << getY() << ")";
return os.str().c_str();
}
};
int main()
{
Vector w1(1.1,2.2);
Vector w2(3.3,4.4);
std::cout << "Vector w1(" << w1.getX() << ","<< w1.getY() << ")"<< std::endl;
std::cout << "Vector w2(" << w2.getX() << ","<< w2.getY() << ")"<< std::endl;
const char* n1 = w1;
const char* n2 = w2;
std::cout << n1 << std::endl;
std::cout << n2 << std::endl;
}
Output of this program:
$ ./a.out
Vector w1(1.1,2.2)
Vector w2(3.3,4.4)
Vector(3.3,4.4)
Vector(3.3,4.4)
I don't understand why I get the output. It seems that "const char* n2 = w2;" overwrites n1 and then I get two times "Vector(3.3,4.4)". Could anybody explain me this phenomena?
It's undefined behavior that sometimes works (by luck), sometimes doesn't.
You're returning a pointer to a temporary local object. The pointer to a temporary local object being the internals of the string object obtained by calling os.str().c_str()
.
If you want print those objects easily by cout
, you can overload operator <<
for output streams. Like:
ostream& operator<<(ostream& out, const Vector &a)
{
std::ostringstream os;
os << "Vector(" << a.getX() << "," << a.getY() << ")";
out << os.str();
return out;
}
and then
std::cout << w1 << std::endl;
std::cout << w2 << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With