运算符重载 c++
我正在尝试在 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){
/* .......... */
}
I am trying to preform operator overloading in C++;
for some reason the compiles keeps on giving me the error
error: ‘bool Matrix::operator==(const Matrix&, const Matrix&)’ must take exactly one argument
Now, I know that there is some way to to it with one argument using this, but I understood that by using friend I can do it this way, but it still is not working.
Here is my code,
Thanks in advance.
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){
/* .......... */
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
operator==
member 函数声明为:operator==
global 函数声明为:一般先声明并定义成员函数。然后,根据成员函数来定义全局函数为只声明和定义成员函数和全局函数之间的一个。对于下面的 (1) 之类的语句来说,同时拥有它们是不明确的
,在这种情况下编译器会返回错误。在g++中,错误消息看起来像
每当
operator==
完成时,建议执行相应的operator!=
。The
operator==
member function is declared as:The
operator==
global function is declared as:Generally, the member function is declared and defined first. Then, the global function is defined in terms of the member function asOnly one between the member function and global function is declared and defined. Having both of them is ambiguous for statements like (1) in the following
and in such cases compiler returns error. In g++, the error message looks like
Whenever
operator==
is done, its recommended to do the correspondingoperator!=
.尽管您已将
friend
声明放入类中,但它不是成员。因此函数定义应该是非成员:您还需要向声明的参数添加 const 限定符,以匹配定义中的参数。
Although you've put the
friend
declaration inside the class, it's not a member. So the function definition should be a non-member:You also need to add
const
qualifiers to the arguments of the declarations, to match those in the definition.在 Visual Studio 2005 中通过编译。
在友元声明中省略 const 限定符
操作中不需要 Matrix::== 定义
Pass compilation in Visual Studio 2005.
omit the const qualifier in your friend declaration
don't need Matrix:: in operation== definition
如果您在类外部而不是作为成员函数执行此操作,则可以使用 2 个参数来执行此操作。
作为成员函数,您只需要 1 个参数(另一个参数是
*this
)You do it with 2 parameters if you are doing it outside of the class, not as a member function.
As a member function you need only 1 parameter (the other parameter is
*this
)