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

Mar*_*cin 6 c++ const overwrite char operator-keyword

#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;
}
Run Code Online (Sandbox Code Playgroud)

该计划的输出:

$ ./a.out 
Vector w1(1.1,2.2)
Vector w2(3.3,4.4)
Vector(3.3,4.4)
Vector(3.3,4.4)
Run Code Online (Sandbox Code Playgroud)

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

mas*_*oud 13

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

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

如果要轻松打印这些对象cout,可以<<使输出流的运算符重载.喜欢:

ostream& operator<<(ostream& out, const Vector &a)
{
   std::ostringstream os;
   os << "Vector(" << a.getX() << "," << a.getY() << ")";
   out << os.str();

   return out;
}
Run Code Online (Sandbox Code Playgroud)

然后

std::cout << w1 << std::endl;
std::cout << w2 << std::endl;
Run Code Online (Sandbox Code Playgroud)