【问题标题】:Return type for the assignment operator赋值运算符的返回类型
【发布时间】:2015-07-16 09:50:52
【问题描述】:

用类名定义的操作符有什么区别:

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;
}

什么时候应该使用第一个,什么时候应该使用第二个?

【问题讨论】:

标签: c++ class c++11


【解决方案1】:

第一个版本允许在一行中对返回的对象进行进一步的操作,如

(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

鉴于返回一个引用真的很便宜,我建议总是返回一个。这将为您省去寻找奇怪错误的痛苦,否则完全合理的语法会破坏您的代码。

【讨论】:

  • @Eiron 这回答了你的问题,还是我误会了你?
猜你喜欢
  • 2021-02-20
  • 1970-01-01
  • 2016-02-01
  • 2017-03-01
  • 2019-12-29
相关资源
最近更新 更多