重载少于运算符 [英] Overloading less than operator

查看:70
本文介绍了重载少于运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这样的类,我正在重载小于操作符:

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

然后是实现文件:

#include "X.h"


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

但是,由于a被声明为私有数据成员,即使它通过X对象,也不允许我访问实现文件中的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?

推荐答案

friend函数与该函数定义的函数没有相同的签名:

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

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

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);
//                        ^^^^^       ^^^^^

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

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

这篇关于重载少于运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆