简体   繁体   English

超载少于运营商

[英]Overloading less than operator

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 a data member in the implementation file because a is declared as a private data member, even though its through an X object? 但是它不允许我访问实现文件中a数据成员,因为a被声明为私有数据成员,即使它是通过X对象?

The friend function does not have the same signature as the function defined function: friend函数与函数定义函数的签名不同:

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. 由于您不修改比较运算符内的对象,因此它们应该采用const引用。

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. 无论如何,比较运算符采用非const引用是没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM