重载的 operator= 返回 void 不可能成为复制赋值运算符吗?
Is it not possible for an overloaded operator= returning void be a copy assignmnent operator?
参考 http://en.cppreference.com/w/cpp/language/as_operator 的页面,复制赋值运算符,由编译器在需要时自动生成,returns 自身类型的左值引用。
所以当我如下定义重载运算符时,
void operator=(T& t)
编译器是否还有机会隐式定义默认的复制赋值运算符?
C++ Reference(正如您自己发现的那样)声明:
If no user-defined copy assignment operators are provided for a class type (struct, class, or union), the compiler will always declare one as an inline public member of the class.
和
A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&
换句话说:一旦声明了自己的复制赋值运算符(采用 T& 参数),编译器就不会添加隐式运算符。
仍然存在为什么要 return void 的问题...(C++ 编码指南建议 return 对自身的引用)
这是 C++11 语言标准指定的复制赋值运算符 [class.copy]/17:
A user-declared copy assignment operator X::operator=
is a non-static non-template member function of class X
with exactly one parameter of type X
, X&
, const X&
, volatile X&
or const volatile X&
.
return 类型不影响它是否被视为复制赋值运算符。它只会影响您可以对赋值表达式的结果执行的操作。
参考 http://en.cppreference.com/w/cpp/language/as_operator 的页面,复制赋值运算符,由编译器在需要时自动生成,returns 自身类型的左值引用。
所以当我如下定义重载运算符时,
void operator=(T& t)
编译器是否还有机会隐式定义默认的复制赋值运算符?
C++ Reference(正如您自己发现的那样)声明:
If no user-defined copy assignment operators are provided for a class type (struct, class, or union), the compiler will always declare one as an inline public member of the class.
和
A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T, T&, const T&, volatile T&, or const volatile T&
换句话说:一旦声明了自己的复制赋值运算符(采用 T& 参数),编译器就不会添加隐式运算符。
仍然存在为什么要 return void 的问题...(C++ 编码指南建议 return 对自身的引用)
这是 C++11 语言标准指定的复制赋值运算符 [class.copy]/17:
A user-declared copy assignment operator
X::operator=
is a non-static non-template member function of classX
with exactly one parameter of typeX
,X&
,const X&
,volatile X&
orconst volatile X&
.
return 类型不影响它是否被视为复制赋值运算符。它只会影响您可以对赋值表达式的结果执行的操作。