<分区>
Possible Duplicate:
Overloading += in c++
如果重载 +,是否需要重载 += 运算符,或者编译器知道该怎么做?
谢谢。
最佳答案
你需要重载两者。
但是,如果您颠倒顺序,您可以重用您的代码:
struct foo
{
// this is the "core" operation, because it's mutating (changes this)
foo& operator+=(const foo&)
{
// ...
return *this;
}
};
foo operator+(const foo& lhs, const foo& rhs)
{
foo ret = lhs;
ret += rhs;
return ret;
}
您创建一个拷贝,对该拷贝进行操作,然后将其返回。
关于c++ - 如果 + 重载,则重载 += 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3525965/