c – operator const char *以奇怪的方式覆盖(?)我的另一个变量

前端之家收集整理的这篇文章主要介绍了c – operator const char *以奇怪的方式覆盖(?)我的另一个变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. class Vector
  5. {
  6. double _x;
  7. double _y;
  8. public:
  9. Vector(double x,double y) : _x(x),_y(y) {}
  10. double getX() { return _x; }
  11. double getY() { return _y; }
  12.  
  13. operator const char*()
  14. {
  15. std::ostringstream os;
  16. os << "Vector(" << getX() << "," << getY() << ")";
  17. return os.str().c_str();
  18. }
  19. };
  20. int main()
  21. {
  22. Vector w1(1.1,2.2);
  23. Vector w2(3.3,4.4);
  24. std::cout << "Vector w1(" << w1.getX() << ","<< w1.getY() << ")"<< std::endl;
  25. std::cout << "Vector w2(" << w2.getX() << ","<< w2.getY() << ")"<< std::endl;
  26.  
  27. const char* n1 = w1;
  28. const char* n2 = w2;
  29.  
  30. std::cout << n1 << std::endl;
  31. std::cout << n2 << std::endl;
  32. }

该计划的输出

  1. $./a.out
  2. Vector w1(1.1,2.2)
  3. Vector w2(3.3,4.4)
  4. Vector(3.3,4.4)

我不明白为什么我得到输出.似乎“const char * n2 = w2;”覆盖n1然后我得到两次“Vector(3.3,4.4)”.有人可以解释一下这种现象吗?

解决方法

这是未定义的行为,有时有效(运气),有时不行.

您正在返回指向临时本地对象的指针.指向临时本地对象的指针是通过调用os.str().c_str()获得的字符串对象的内部.

如果你想通过cout轻松打印这些对象,你可以重载operator<<用于输出流.喜欢:

  1. ostream& operator<<(ostream& out,const Vector &a)
  2. {
  3. std::ostringstream os;
  4. os << "Vector(" << a.getX() << "," << a.getY() << ")";
  5. out << os.str();
  6.  
  7. return out;
  8. }

然后

  1. std::cout << w1 << std::endl;
  2. std::cout << w2 << std::endl;

猜你在找的C&C++相关文章