c++ - 运算符重载 C++

标签 c++ operator-overloading friend

我正在尝试在 C++ 中执行运算符重载; 由于某种原因,编译不断给我错误

error: ‘bool Matrix::operator==(const Matrix&, const Matrix&)’ must take exactly one argument

现在,我知道有一些方法可以通过使用 this 的一个参数来实现它,但我知道通过使用 friend 我可以这样做,但它仍然不起作用。

这是我的代码,

提前致谢。

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){

/* .......... */
}

最佳答案

operator== member 函数声明为:

class foo {
  public:
    bool operator==( foo const & rhs ) const;
};

operator== global 函数声明为:

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!=

关于c++ - 运算符重载 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3756180/

相关文章:

c++ - 如何声明两个类使得 A 具有 B 的成员并且 B 将 A 的成员标记为 friend ?

C++ : Undefined symbols for architecture x86_64 on MacOS Mountain Lion

c++ - 将两次 "for"循环更改为单个 "for"循环(排序)

c# - 实现特定运算符的对象的 .NET 接口(interface)/约束

c++ - operator new 和 operator new[] 的区别?

c++ - friend 模板运算符<<无法访问类的保护成员

c++ - 显式类型标识符与 RTTI

c++ - 如何使子控件处理父 CView 的加速器命令

c++ - C++ 中的运算符优先级重载

c++ - 访问私有(private)类或 protected 类的构造函数?