c++ - 在函数中使用时自己的 operator+ 的奇怪行为(Point3D(0,0,0)+ 点)

标签 c++ operators operator-overloading overloading

我有一个类:

class Point3D : public Point{
    protected:
        float x;
        float y;
        float z;

    public:
        Point3D(){x=0; y=0; z=0;}
        Point3D(const Point3D & point){x = point.x; y = point.y; z = point.z;} 
        Point3D(float _x,float _y,float _z){x = _x; y = _y; z = _z;}

        inline const Point3D operator+(const Vector3D &);

        const Point3D & operator+(const Point3D &point){
            float xT = x + point.getX();
            float yT = y + point.getY();
            float zT = z + point.getZ();
            return Point3D(xT, yT, zT);
        }
...

当我这样使用它时:

Point3D point = Point3D(10,0,10);

一切正常。

当我写的时候:

Point3D point = Point3D(10,0,10);
Point3D point2 = Point3D(0,0,0) + point();

也没关系(point2 = point)。当我添加超过 (0,0,0) 的内容时,它也有效。

但是当我只想:

Point3D point = Point3D(10,0,10);
someFunction( Point3D(0,0,0) + point ); //will get strange (x,y,z)

该函数获取一些(在我看来)随机 (x,y,z) 的值。为什么?

更奇怪的是,在那个类似的例子中,一切都将再次工作:

Point3D point = Point3D(10,0,10);
Point3D point2 = Point3D(0,0,0) + point;
someFunction( point2 );  // will get (10,0,10)

这种奇怪行为的原因是什么?

最佳答案

operator+() 返回一个悬空引用,返回的引用指向一个 Point3D 实例,当 operator+() 时被销毁返回。更改为:

Point3D operator+(const Point3D &point) const {

因此返回一个拷贝,并使其成为const,因为它没有理由改变任何东西。

关于c++ - 在函数中使用时自己的 operator+ 的奇怪行为(Point3D(0,0,0)+ 点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11340677/

相关文章:

c++ - 当我不知道 `std::unique_ptr<Base>(ptr)` 是如何分配的时, `ptr` 的销毁策略?

c++ - 实现模板运算符非友元

c# - 的正确名称是什么??运算符(operator)?

c++ - 未能重载运算符<< (c++)

C++ on Xcode 7.01 on El Capitan Error -> Undefined symbols for architecture x86_64 :

c++ - 从无符号除法的结果分配时出现符号转换警告

Python 不等式 : ! = vs 不 ==

c++ - 类中的运算符如何工作?

C++ "<<"运算符重载

C++ 重载运算符返回派生类对象而不是基类