我有一个班级:
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)
这种奇怪行为的原因是什么?
答案 0 :(得分:4)
operator+()
返回一个悬空引用,返回的引用引用Point3D
实例,该实例在operator+()
返回时被销毁。改为:
Point3D operator+(const Point3D &point) const {
因此返回副本,并将其设为const
,因为它没有理由改变任何内容。
答案 1 :(得分:3)
支持算术运算符的类的典型模式是
class Foo
{
public:
Foo & operator+=(Foo const & rhs) { /* ... */ return *this; }
Foo & operator-=(Foo const & rhs) { /* ... */ return *this; }
Foo & operator*=(Foo const & rhs) { /* ... */ return *this; }
Foo & operator/=(Foo const & rhs) { /* ... */ return *this; }
};
Foo operator+(Foo const & lhs, Foo const & rhs) { return Foo(lhs) += rhs; }
Foo operator-(Foo const & lhs, Foo const & rhs) { return Foo(lhs) -= rhs; }
Foo operator*(Foo const & lhs, Foo const & rhs) { return Foo(lhs) *= rhs; }
Foo operator/(Foo const & lhs, Foo const & rhs) { return Foo(lhs) /= rhs; }
答案 2 :(得分:2)
您正在返回对operator+
的局部变量的引用,该函数在函数返回后将失效,您需要返回已创建的Point3D
的副本。