超载少于运营商

use*_*112 3 c++ operator-overloading

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

#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;
};
Run Code Online (Sandbox Code Playgroud)

然后执行文件:

#include "X.h"


bool operator < (X const& lhs, X const& rhs)
{
    return lhs.a< rhs.a;
}
Run Code Online (Sandbox Code Playgroud)

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

Pie*_*aud 12

friend函数与函数定义函数的签名不同:

friend bool operator< (X& a, X& b);
Run Code Online (Sandbox Code Playgroud)

bool operator < (X const& lhs, X const& rhs)
//                 ^^^^^         ^^^^^
Run Code Online (Sandbox Code Playgroud)

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

friend bool operator< ( X const& a, X const& b);
//                        ^^^^^       ^^^^^
Run Code Online (Sandbox Code Playgroud)

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


jua*_*nza 7

您已声明了与您尝试使用的功能不同的朋友功能.你需要

friend bool operator< (const X& a, const X& b);
//                     ^^^^^       ^^^^^
Run Code Online (Sandbox Code Playgroud)

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