gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:36:07 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com