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

C++ 在运算符重载定义中使用成员函数(常量错误),c++,constants,overloading,operator-keyword,C++,Constants,Overloading,Operator Keyword,运算符重载定义中出现错误。如果我删除参数中的常量,错误就会消失。有没有什么方法可以让它在不删除参数中的常量的情况下工作?他们背后发生了什么 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, con

运算符重载定义中出现错误。如果我删除参数中的常量,错误就会消失。有没有什么方法可以让它在不删除参数中的常量的情况下工作?他们背后发生了什么

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

float-dot(Vector3D-const&v)const{/您应该将成员函数
dot
也限定为
const
,否则您不能在
const
对象上调用此成员函数:

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

float-dot(Vector3D-const&v)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);
}

您没有包含该错误,但它的内容类似于:“无法在常量对象上调用非常量方法”。您的
不修改成员,应声明为
常量
,并且参数未修改,因此应为
常量

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
定义中添加两个
const
s

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) :告诉用户成员函数调用的对象未在
Vector3D::dot
函数中修改,成员函数调用的对象和参数对象均未修改

要告诉编译器这一点,您应该在
dot
定义中添加两个
const
s

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):告知成员函数调用的对象未修改

您只需定义成员函数
dot
const问题在于您的成员函数需要为const。最好将其设置为非成员函数,因为它可以使用公共接口计算点积。请参阅Scott Meyers的算法在“.@cdhowie”中,何时使某个对象成为成员函数,它实际上需要是
float-dot(const-Vector3D&v)const{
事实上,错过了参数…您只需要定义成员函数
dot
const问题是您的成员函数需要是const。最好只是将其设为非成员函数,因为它可以使用公共接口计算点积。有关何时将某个函数设为memb,请参阅Scott Meyers的算法“.@cdhowie”中的er函数实际上需要是
float-dot(const-Vector3D&v)const{
确实,没有找到参数。。。