C++ 重载小于运算符
对于这样的类,我重载了一个小于运算符:C++ 重载小于运算符,c++,operator-overloading,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; }; #包括 使用名称空间std; X类{ 公众: X(长a,字符串b,i
#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;
};
#包括
使用名称空间std;
X类{
公众:
X(长a,字符串b,int c);
friend bool运算符<(X&a、X&b);
私人:
长a;
b串;
INTC;
};
然后是实现文件:
#include "X.h"
bool operator < (X const& lhs, X const& rhs)
{
return lhs.a< rhs.a;
}
#包括“X.h”
布尔运算符<(X常量和左侧、X常量和右侧)
{
返回左侧a<右侧a;
}
但是,它不允许我访问实现文件中的
a
数据成员,因为a
被声明为私有数据成员,即使它是通过X
对象实现的?您已经声明了与您尝试使用的函数不同的友元函数。你需要
friend bool operator< (const X& a, const X& b);
// ^^^^^ ^^^^^
friend bool操作符<(常数X&a,常数X&b);
// ^^^^^ ^^^^^
在任何情况下,比较运算符采用非常量引用都没有意义。友元函数与函数定义的函数没有相同的签名:
friend bool operator< (X& a, X& b);
friend bool操作符<(X&a,X&b);
及
bool运算符<(X常量和左侧、X常量和右侧)
// ^^^^^ ^^^^^
您只需将头文件中的行更改为:
friend bool operator< ( X const& a, X const& b);
// ^^^^^ ^^^^^
friend bool操作符<(X常量&a,X常量&b);
// ^^^^^ ^^^^^
由于不修改比较运算符内的对象,因此它们应采用常量引用
friend bool operator< ( X const& a, X const& b);
// ^^^^^ ^^^^^