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

标签 c++ char constants operator-keyword overwrite

#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/

相关文章:

C++ typedef 类使用

c++ - 为什么我们不能直接使用类模板来推导方法模板?新加坡金融学会

java - 在 Java 中将 char[] 转换为 BLOB

c++ - 为什么一个常量整数指针允许指向一个非常量整数?

c - 为什么我不能在 C 中将 'char**' 转换为 'const char* const*'?

C++通过指针填充数组

c++ - 将文件作为参数从 Swift 传递给 C++ 方法

C 字符串分离

c - char 数组是否需要比您打算使用的大一个字节? - C

c - 如何使用 C 中先前定义的常量来定义静态常量?