我正在阅读有关 C++ 中的运算符重载的信息,我已经阅读了很多教程文档和问答,但我找不到答案。 在下面的代码中:
class Box
{
public:
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
int main( )
{
Box Box1;
Box Box2;
Box Box3;
// Add two object as follows:
Box3 = Box1 + Box2;
return 0;
}
如您所见,我们为 BOX 类覆盖了 + 运算符。当我们在 main 函数中调用覆盖运算符时,哪个类实例用作参数(Box1 或 Box2?)&被 this 访问?实际上哪个叫覆盖运算符?为什么我们在参数中使用 & 关键字?世界BR。
最佳答案
左边的操作数是 this
参数。为避免这种晦涩难懂和一些更实际的重要问题,只需将此运算符定义为类外的普通(运算符)函数即可。但是,修改的运算符(例如 +=
)在 IMO 中最好定义为类成员。
课外定义:
class Box
{
private:
// Data members, unspecified in the question.
public:
// Public interface.
};
// Overload + operator to add two Box objects.
auto operator+( Box const& a, Box const& b)
-> Box
{
Box result;
result.length = a.length + b.length;
result.breadth = a.breadth + b.breadth;
result.height = a.height + b.height;
return result;
}
如果你的数据成员不是public
(你没有指定任何关于它的),那么对于上面的类外方法你需要添加一个friend
运算符函数的声明,在类中。例如
friend auto operator+( Box const& a, Box const& b) -> Box;
与类外定义效果几乎相同的替代方法是将运算符定义为类内的friend
函数,如下所示:
class Box
{
private:
// Data members, unspecified in the question.
public:
// Public interface.
friend
auto operator+( Box const& a, Box const& b)
-> Box
{
Box result;
result.length = a.length + b.length;
result.breadth = a.breadth + b.breadth;
result.height = a.height + b.height;
return result;
}
};
在这里你不需要一个单独的friend
声明。
另一个区别是这个类内定义的 friend
函数只能通过参数相关查找 (ADL) 找到,这意味着它并不容易,例如取它的地址。我不知道如何做到这一点。但至少了解这种方法对于理解某些习语是必要的,例如 Barton Nackman 基于 CRTP 的技巧,用于为类赋予关系运算符。
回复
” why we use
&
keyword in argument?
...这只是一个约定,总体上是一种优化,避免了一些不必要的数据复制。然而,对于小型类型,在现代机器上,它可能会产生相反的效果。
关于c++ - 在 C++ 中重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38157326/