这是为什么执行:C++ - 为什么要op + =而不是其他方式实现op +?
T& T::operator+=(const T&) {
// ... implementation ...
return *this;
}
T operator+(const T& lhs, const T& rhs) {
T temp(lhs);
return temp += rhs;
}
传播更多的时候比这一个:
T& T::operator+=(const T& rhs) {
*this = *this + rhs;
return *this;
}
T operator+(const T& lhs, const T& rhs) {
// ... implementation ...
return some_result;
}
没有任何理由可言,还是仅仅是我见过的人实现它随机的巧合这种方式多次在我阅读的文献中,而且从来没有其他方式?
测试第二个,你会发现它不起作用。究竟它是如何工作的将取决于'// ...实现...'中发生了什么,但它不会起作用。最有可能的是,'return * this + rhs;'完全不会对'this'做任何事情。 – user2357112
@ user2357112:我的回答是解释你发现的问题,还是另一个? –
请不要通过查看答案来更改帖子。它会使答案无效 – P0W