C++ 重载 operator== 抱怨“必须只采用一个参数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11229074/
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 14:58:40  来源:igfitidea点击:

overloading operator== complaining of 'must take exactly one argument'

c++

提问by chlong

I am trying to overload the operator==, but the compiler is throwing the following error:

我试图重载operator==,但编译器抛出以下错误:

‘bool Rationalnumber::operator==(Rationalnumber, Rationalnumber)' must take exactly one argument

My short piece of code is as follows:

我的一小段代码如下:

bool Rationalnumber::operator==(Rationalnumber l, Rationalnumber r) {
  return l.numerator() * r.denominator() == l.denominator() * r.numerator();
}

Declaration:

宣言:

bool operator==( Rationalnumber l, Rationalnumber r );

Does anyone have any ideas why it's throwing the error?

有没有人知道为什么会抛出错误?

回答by juanchopanza

If operator==is a non static data member, is should take only one parameter, as the comparison will be to the implicit thisparameter:

如果operator==是非静态数据成员,则应该只带一个参数,因为比较将与隐式this参数进行比较:

class Foo {
  bool operator==(const Foo& rhs) const { return true;}
};

If you want to use a free operator (i.e. not a member of a class), then you can specify two arguments:

如果要使用自由运算符(即不是类的成员),则可以指定两个参数:

class Bar { };
bool operator==(const Bar& lhs, const Bar& rhs) { return true;}

回答by Plexico

As a memberoperator overload it should only take one argument, the other being this.

作为成员运算符重载,它应该只接受一个参数,另一个是this.

class Foo
{
    int a;

public:
    bool operator==(const Foo & foo);
};

//...

bool Foo::operator==(const Foo & foo)
{
    return a == foo.a;
}

回答by tim-oleksii

You should remove your operator== from a RationalNumber to somewhere else. As it is declared inside a class it is considered that 'this' is the first argument. From semantics it is seen that you offer 3 arguments to a compiler.

您应该将您的 operator== 从 RationalNumber 删除到其他地方。由于它是在类中声明的,因此认为“this”是第一个参数。从语义上可以看出,您向编译器提供了 3 个参数。

回答by yucun li

friend bool operator==( Rationalnumber l, Rationalnumber r );

when you declare it as non-member function, it can take two arguments. when you declare it as member function, it can only take one argument.

当你将它声明为非成员函数时,它可以接受两个参数。当你将它声明为成员函数时,它只能接受一个参数。