在函数中使用时自己的运算符+的奇怪行为(Point3D(0,0,0)+点)
Strange behaviour of own operator+ when using in function ( Point3D(0,0,0) + point)
我有一个类:
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();
也可以(点2 =点)。当我添加超过 (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
,因为它没有理由更改任何内容。
支持算术运算符的类的典型模式是
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; }
您正在从 operator+
返回对局部变量的引用,一旦函数返回,该引用将失效,您需要返回创建的Point3D
的副本。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 在函数中使用时自己的运算符+的奇怪行为(Point3D(0,0,0)+点)