#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; }
The 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 do not understand why I get the conclusion. It seems that "const char * n2 = w2;" overwrites n1 and then I get Vector twice (3.3.4.4). "Can someone explain these phenomena to me?
source share