gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:11:11 27 4
gpt4 key购买 nike

#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)
Vector(3.3,4.4)

我不明白为什么会得到输出。似乎是“const char* n2 = w2;”覆盖 n1 然后我得到两次“Vector(3.3,4.4)”。谁能给我解释一下这种现象?

最佳答案

未定义的行为有时有效(靠运气),有时无效。

您正在返回一个指向临时本地对象的指针。指向临时本地对象的指针是通过调用 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;
}

然后

std::cout << w1 << std::endl;
std::cout << w2 << std::endl;

关于c++ - operator const char* 以奇怪的方式覆盖(?)我的另一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20072202/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com