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)
该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!=.
虽然您已将friend声明放在课堂内,但它不是会员.所以函数定义应该是非成员:
inline bool operator==(const Matrix& mtrx1, const Matrix& mtrx2) {...}
Run Code Online (Sandbox Code Playgroud)
您还需要const在声明的参数中添加限定符,以匹配定义中的参数.
| 归档时间: |
|
| 查看次数: |
2160 次 |
| 最近记录: |