分配运算符的返回类型
Return type for the assignment operator
用其类名称定义的操作员有什么区别:
class RefObj {
public:
RefObj &operator=(const RefObj &) { return *this; }
private:
int m_Counter = 0;
};
和一个带有void的操作员:
template<class T> class SmartPtr {
public:
void operator=(T* pointer) { m_SmartPtr = pointer; }
private:
T* m_SmartPtr;
}
我什么时候应该使用第一个,什么时候应该使用第二个?
第一个版本允许在一行中对返回对象进行进一步的操作,如
中的(refobj = a).do_something();
当您不返回对对象的引用时,这是不可能的。您可能会认为这很愚蠢,但请考虑输出操作员。
void operator<<(std::ostream &out, const Obj1 &obj1);
std::ostream& operator<<(std::ostream &out, const Obj2 &obj2);
Obj1 obj1;
Obj2 obj2;
std::cout << obj1 << 't' << obj1 << std::endl; // compiler error
// ^^^^ '<<' can't operate on void
std::cout << obj2 << 't' << obj2 << std::endl; // works!
// ^^^^ return type is std::ostream, '<<' work on that
鉴于返回参考真的很便宜,我建议始终返回一个。这将为您节省搜索奇怪的错误的痛苦,否则完美的理智语法会破坏您的代码。
相关文章:
- 为什么重载运算符可以返回其返回类型以外的其他内容?
- 错误:为"运算符 std::string {aka std::__cxx11::basic_string}"指定的返回类型<char>
- 运算符和返回类型是什么意思?
- 为什么类的赋值运算符的返回类型通常是非常量(而不是常量)引用?
- 如何确定三元运算符的返回类型?
- 如何使模板化运算符推断出正确的返回类型
- 根据运算符推断模板返回类型:结果
- 重写运算符的返回类型=
- 错误:"运算符="不匹配 |结构返回类型
- 使用 std::function 时选择自动返回类型而不是构造函数的调用运算符
- 条件运算符的返回类型和两阶段查找
- 如何使用内置返回类型重载运算符?
- 分配运算符的返回类型
- 为什么+运算符重载返回类型是类类型而不是整数
- 如何判断"->"运算符最终是否返回类型?
- 重载运算符:常量与非常量返回类型:任何性能差异
- 流运算符重载中的返回类型
- 模板类中运算符*的尾随返回类型
- 返回类型 ?:运算符和 C++ Primer 中的措辞
- 返回类型与返回类型(运算符++)不相同,也不协变