【问题标题】:Overloading the == function重载 == 函数
【发布时间】:2012-03-09 09:31:19
【问题描述】:

我目前正在为 == 运算符创建一个重载函数。我正在为我的链表创建一个 hpp 文件,但我似乎无法让这个运算符在 hpp 文件中工作。

我目前有这个:

template <typename T_>
class sq_list 
{

bool operator == ( sq_list & lhs, sq_list & rhs) 
{
    return *lhs == *rhs;
};

reference operator * ()     {
        return _c;
    };

};
}

我收到了大约 10 个错误,但它们几乎都以错误的形式重复:

C2804:二进制 'operator ==' 参数过多
C2333:'sq_list::operator ==' : 函数声明错误;跳过函数体
C2143:语法错误:缺少“;”在'*'之前
C4430:缺少类型说明符 - 假定为 int。注意:C++ 不支持 default-int

我尝试过改变,但总是遇到与上述相同的错误

非常感谢任何提示或帮助。

【问题讨论】:

  • 如果它是一个成员函数,它需要一种艺术并使用它
  • @awoodland:不,你没有;在类模板定义中,模板名称可以单独引用当前模板实例。无论如何,OP 的代码中都没有 T

标签: c++ templates operators operator-overloading equals-operator


【解决方案1】:

成员运算符只有一个参数,即另一个对象。第一个对象是实例本身:

template <typename T_>
class sq_list 
{
    bool operator == (sq_list & rhs) const // don't forget "const"!!
    {
        return *this == *rhs;  // doesn't actually work!
    }
};

这个定义实际上没有意义,因为它只是递归地调用自己。相反,它应该调用一些成员操作,例如return this-&gt;impl == rhs.impl;

【讨论】:

    【解决方案2】:

    您将 == 重载声明为类定义的一部分,因为方法实例将获得。因此,您请求的第一个参数 lhs 已经是隐含的:请记住,在实例的方法中,您可以访问 this

    class myClass {
        bool operator== (myClass& other) {
            // Returns whether this equals other
        }
    }
    

    作为类的一部分的 operator==() 方法应该被理解为“这个对象知道如何将自己与其他对象进行比较”。

    您可以在类外部重载 operator==() 以接收两个参数,两个对象都被比较,如果这对您更有意义的话。看这里: http://www.learncpp.com/cpp-tutorial/94-overloading-the-comparison-operators/

    【讨论】:

      【解决方案3】:

      http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html

      比较运算符非常简单。首先定义 ==,使用这样的函数签名:

        bool MyClass::operator==(const MyClass &other) const {
          ...  // Compare the values, and return a bool result.
        }
      

      如何比较 MyClass 对象是您自己的事。

      【讨论】:

        猜你喜欢
        • 2014-06-18
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 2017-08-06
        • 2018-03-05
        • 2020-03-23
        相关资源
        最近更新 更多