运算符重载c ++

bas*_*ass 0 c++ operator-overloading friend

我试图在C++中预先形成运算符重载; 由于某种原因,编译继续给我错误

错误:'bool Matrix :: operator ==(const Matrix&,const Matrix&)'必须只有一个参数

现在,我知道有一些方法可以用一个参数使用它,但我明白通过使用朋友我可以这样做,但它仍然无法正常工作.

这是我的代码,

提前致谢.

class Matrix{
public:
 Matrix();
 friend bool operator==(Matrix &mtrx1,Matrix &mtrx2);
 friend bool operator!=(Matrix &mtrx1,Matrix &mtrx2);

protected:
 std::vector<Cell> _matrix;
 int _row;
 int _col;

};

inline bool Matrix::operator==(const Matrix& mtrx1, const Matrix& mtrx2){

/* .......... */
}
Run Code Online (Sandbox Code Playgroud)

Aru*_*run 8

operator== 成员函数声明为:

class foo {
  public:
    bool operator==( foo const & rhs ) const;
};
Run Code Online (Sandbox Code Playgroud)

operator== 全局函数声明为:

bool operator==( foo const & lhs, foo const & rhs );
Run Code Online (Sandbox Code Playgroud)

通常,首先声明和定义成员函数.然后,全局函数根据成员函数定义

声明和定义成员函数和全局函数之间只有一个.对于如下面的(1)的陈述,它们两者都是模糊的

foo f1;
foo f2;
bool f1EqualsF2 = (f1 == f2 );  // (1), ambiguous
Run Code Online (Sandbox Code Playgroud)

在这种情况下编译器返回错误.在g ++中,错误消息看起来像

equals.cpp:24: error: ambiguous overload for ‘operator==’ in ‘f1 == f2’
equals.cpp:8: note: candidates are: bool foo::operator==(const foo&) const
equals.cpp:17: note:                 bool operator==(const foo&, const foo&)
Run Code Online (Sandbox Code Playgroud)

无论何时operator==完成,建议做相应的operator!=.

  • 这是错的.通常你要么定义一个成员函数_or_你定义一个自由函数.你不应该定义两者,否则`a == b`通常是模糊的.通常首选自由函数,因为它导致左右操作数的一致隐式转换规则.就目前而言,你不能把`lhs.operator ==(rhs)`作为`operator ==`是一个非`constst`成员函数,在`foo`中是`private`. (2认同)

Mik*_*our 5

虽然您已将friend声明放在课堂内,但它不是会员.所以函数定义应该是非成员:

inline bool operator==(const Matrix& mtrx1, const Matrix& mtrx2) {...}
Run Code Online (Sandbox Code Playgroud)

您还需要const在声明的参数中添加限定符,以匹配定义中的参数.