C++ 重载小于运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18646526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:05:22  来源:igfitidea点击:

Overloading less than operator

c++operator-overloading

提问by user997112

I am overloading a less than operator for a class like so:

我正在为一个类重载一个小于运算符,如下所示:

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

and then the implementation file:

然后是实现文件:

#include "X.h"


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

However it is not letting me access the adata member in the implementation file because ais declared as a private data member, even though its through an Xobject?

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

回答by Pierre Fourgeaud

The friend function does not have the same signature as the function defined function:

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

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

and

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

You should just change the line in your header file to:

您应该将头文件中的行更改为:

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

As you don't modify the objects inside the comparison operators, they should take const-references.

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

回答by juanchopanza

You have declared a different friend function to the one you are trying to use. You need

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

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

In any case, it would make no sense for a comparison operator to take non-const references.

在任何情况下,比较运算符采用非常量引用都是没有意义的。