#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; }
该计划的输出:
$./a.out Vector w1(1.1,2.2) Vector w2(3.3,4.4) Vector(3.3,4.4)
我不明白为什么我得到输出.似乎“const char * n2 = w2;”覆盖n1然后我得到两次“Vector(3.3,4.4)”.有人可以解释一下这种现象吗?
解决方法
这是未定义的行为,有时有效(运气),有时不行.
您正在返回指向临时本地对象的指针.指向临时本地对象的指针是通过调用os.str().c_str()获得的字符串对象的内部.
如果你想通过cout轻松打印这些对象,你可以重载operator<<用于输出流.喜欢:
ostream& operator<<(ostream& out,const Vector &a) { std::ostringstream os; os << "Vector(" << a.getX() << "," << a.getY() << ")"; out << os.str(); return out; }
然后
std::cout << w1 << std::endl; std::cout << w2 << std::endl;