我在运算符重载定义中遇到错误。 如果我移除参数中的consts,错误就会消失。 有没有什么方法可以让它工作而不删除参数中的consts? 还有他们背后发生了什么?
class Vector3D{
public:
float x, y, z;
float dot(Vector3D& v) {
return x * v.x + y * v.y + z * v.z;
}
};
inline float operator *(const Vector3D& a, const Vector3D& b) {
return a.dot(b);
}
您还应将成员函数dot
限定为const
,否则您无法在const
对象上调用此成员函数:
float dot(Vector3D const& v) const { // <-- const here
您还需要接受v
byconst&
,因为您正在向它传递一个const
对象。
您没有包括错误,但它说:“不能在const对象上调用非const方法”。 您的dot
不修改成员,应声明为const
参数也未修改,因此应为const
:
class Vector3D{
public:
float x, y, z;
// v---------------- allow to call on const objects
float dot(const Vector3D& v) const {
// ^---------------------------------- pass parameters as const ref
return x * v.x + y * v.y + z * v.z;
}
};
inline float operator *(const Vector3D& a, const Vector3D& b) {
return a.dot(b);
}
在Vector3D::dot
函数中,成员函数调用的对象和参数对象都没有修改。
要告诉编译器这一点,您应该在dot
定义中添加两个常量
。
class Vector3D{
public:
float x, y, z;
float dot(const /*(1)*/ Vector3D& v) const /*(2)*/ {
return x * v.x + y * v.y + z * v.z;
}
};
inline float operator *(const Vector3D& a, const Vector3D& b) {
return a.dot(b);
}
(1):告知参数对象未被修改
(2):告知成员函数调用的对象未被修改