运算符重载

Chu*_*dad 8 c++ operator-overloading

为什么重载operator =强制要求成为成员函数($ 13.5.3),而不是复合赋值运算符,例如operator + =($ 13.5.2)?我在这里俯瞰什么吗?

Mot*_*tti 2

您引用的部分有关于隐藏基类实现的内容operator=

operator=因为如果用户未声明,则为类隐式声明复制赋值运算符 (12.8),

这也可能是您问题的答案,因为编译器需要知道是否应该生成一个它operator=必须知道是否定义了这样的运算符,如果可以在类之外定义它,则编译器无法知道它是否在类中定义不同的翻译单位。

例如

//a.h
class A { }; // compiler thinks A::operator= should be implicitly defined

//b.h
#include "a.h"
A& operator=(A& This, const A& other) { /*...*/ } // Oops it's explicitly defined
Run Code Online (Sandbox Code Playgroud)

另一方面,复合运算符不是隐式定义的,因此没有理由强制将它们声明为成员函数。