提问者:小点点

在运算符重载定义中使用成员函数(常量错误)


我在运算符重载定义中遇到错误。 如果我移除参数中的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);
}

共3个答案

匿名用户

您还应将成员函数dot限定为const,否则您无法在const对象上调用此成员函数:

float dot(Vector3D const& v) const {  // <-- const here

您还需要接受vbyconst&,因为您正在向它传递一个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):告知成员函数调用的对象未被修改