【问题标题】:Using member functions in operator overloading definition (error with const)在运算符重载定义中使用成员函数(const 错误)
【发布时间】:2020-07-08 13:03:25
【问题描述】:

我在运算符重载定义中遇到错误。如果我删除参数中的 const,错误就会消失。有什么方法可以在不删除参数中的 const 的情况下使其工作?还有他们背后发生了什么?

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);
}

【问题讨论】:

  • 只需要定义成员函数dotconst
  • 问题是你的成员函数需要是const。最好将其设为非成员函数,因为它可以使用公共接口来计算点积。请参阅 Scott Meyers 的算法,了解何时将某事设为“How Non-Member Functions Improve Encapsulation”中的成员函数。
  • @cdhowie 其实应该是float dot(const Vector3D &v) const {
  • 确实,错过了争论......

标签: c++ constants overloading operator-keyword


【解决方案1】:

您也应该将成员函数dot 限定为const,否则您不能在const 对象上调用此成员函数:

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

您还需要通过const&amp; 接受v,因为您传递的是const 对象。

【讨论】:

    【解决方案2】:

    您没有包含错误,但它说的是:“无法在 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);
    }
    

    【讨论】:

      【解决方案3】:

      Vector3D::dot函数中,成员函数调用的对象和参数对象都没有被修改。

      要将这一点告诉编译器,您应该将两个 consts 添加到您的 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):告诉成员函数调用的对象没有被修改

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-06-05
        • 2014-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        相关资源
        最近更新 更多