运算符重载C++
我想在C++中执行操作符重载; 由于某些原因,编译不断给我的错误运算符重载C++
error: ‘bool Matrix::operator==(const Matrix&, const Matrix&)’ must take exactly one argument
现在,我知道有一些方法来给它用这一个说法,但我明白,用的朋友,我可以这样来做,但它仍然无法正常工作。
这是我的代码,
在此先感谢。
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){
/* .......... */
}
虽然你已经把friend
声明的类里面,它不是一个成员。因此,函数定义应该是一个非成员:
inline bool operator==(const Matrix& mtrx1, const Matrix& mtrx2) {...}
还需要const
预选赛添加到声明的参数,以匹配的定义。
我试图改变它..它仍然给出了同样的错误:( – bass 2010-09-20 23:17:49
但是,请注意,'朋友'声明强制它是一个非成员,所以即使你在类定义内原地定义它,它真的是一个全球性的功能! – 2010-09-20 23:19:40
@Jerry Coffin:或者更严格的说是一个属于内部命名空间的函数,它包含给定的类 – 2010-09-21 07:25:50
如果您在课堂外进行操作,而不是作为成员函数,则可以使用2个参数进行操作。
当你只需要1个参数的成员函数(另一个参数是*this
)
...如果你作为类的一部分实现,你将不需要朋友 – 2010-09-20 23:17:03
为operator==
成员函数声明:
class foo {
public:
bool operator==(foo const & rhs) const;
};
的operator==
全球函数声明为:
bool operator==(foo const & lhs, foo const & rhs);
通常,首先声明和定义成员函数。然后,全局函数根据成员函数定义为:
只声明和定义了成员函数和全局函数之间的函数。有两个他们是歧义(1)在以下语句
foo f1;
foo f2;
bool f1EqualsF2 = (f1 == f2); // (1), ambiguous
并在这种情况下编译器返回错误。在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&)
每当operator==
完成后,其建议做相应的operator!=
。
不要忘记方法操作符的const ==() – 2010-09-21 05:43:59
这是错误的,一般来说你要么定义一个成员函数,要么定义一个*函数,否则你不应该定义两个'a == b'一般是含糊不清,*函数通常是首选,因为它导致了左和右操作数的一致隐式转换规则,因为'operator =='不是'lhs.operator ==(rhs)' -'stst'米ember函数,在'foo'中是'private'。 – 2010-09-21 06:41:23
感谢Martin York和Charles Bailey(+1给他们);我在答案中做了一些更正(在成员函数中添加了'const',并在'public'限定符中添加了'const')。 – Arun 2010-09-21 14:42:34
class Matrix{
public:
Matrix();
friend bool operator==(const Matrix &mtrx1, const Matrix &mtrx2);
friend bool operator!=(const Matrix &mtrx1, const Matrix &mtrx2);
protected:
std::vector<Cell> _matrix;
int _row;
int _col;
};
inline bool operator==(const Matrix& mtrx1, const Matrix& mtrx2){
/* .......... */
return true;
}
在Visual Studio 2005中通过编译。
省略const限定在你的朋友声明
不需要矩阵::在操作==定义
很好地格式化代码,用4个空格缩进它,或者选择它并按下0和1的按钮。 – 2010-09-20 23:17:03