【问题标题】:Overloading less than operator重载小于运算符
【发布时间】:2013-09-05 21:49:10
【问题描述】:

我正在为这样的类重载小于运算符:

#include<string>
using namespace std;

class X{
public:
    X(long a, string b, int c);
    friend bool operator< (X& a, X& b);

private:
    long a;
    string b;
    int c;
};

然后是实现文件:

#include "X.h"


bool operator < (X const& lhs, X const& rhs)
{
    return lhs.a< rhs.a;
}

但是它不允许我访问实现文件中的a 数据成员,因为a 被声明为私有数据成员,即使它是通过X 对象?

【问题讨论】:

    标签: c++ operator-overloading


    【解决方案1】:

    友元函数与函数定义函数的签名不同:

    friend bool operator< (X& a, X& b);
    

    bool operator < (X const& lhs, X const& rhs)
    //                 ^^^^^         ^^^^^
    

    您只需将头文件中的行更改为:

    friend bool operator< ( X const& a, X const& b);
    //                        ^^^^^       ^^^^^
    

    由于您不修改比较运算符中的对象,因此它们应该采用 const 引用。

    【讨论】:

      【解决方案2】:

      您已经声明了一个与您尝试使用的函数不同的友元函数。你需要

      friend bool operator< (const X& a, const X& b);
      //                     ^^^^^       ^^^^^
      

      无论如何,比较运算符采用非常量引用是没有意义的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多