我有一个带有一对函数调用操作符的函数对象A(第4行和第5行):
class A{
public:
A(int x) : _x(x){}
int operator () () const { return _x; } // line 4
int & operator () () { return _x; } // line 5
private:
int _x;
};
使用类似的一对呼叫运算符here。问题是:我是否需要第4行?第4行定义的运算符是否会被调用?在以下情况中:
A a(7);
a() = 8;
cout << a() << endl;
始终调用第5行的运算符。
答案 0 :(得分:4)
是的,将使用第4行,例如:
A a(3);
const A b(2);
a(); // from line 5
b(); // from line 4
答案 1 :(得分:3)
int operator () () const { return _x; }
当您的对象为const
时,将调用。
同样返回引用不是最好的设计,它打破了数据隐藏规则,set/get
函数是更好的选择。当您调用第4行或调用第5行时,您会感到困惑。
我建议改写为:
class A{
public:
explict A(int x) : x_(x) {}
//int operator () () const { return x_; } // leave operator() for functor.
operator int() const { return x_; } // use conversion function instead
void setX(int x) { x_ = x; }
private:
int x_; //suggest use trailing `_`
};