4

I have a function object A with a pair of function call operators (line 4 and 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; 
};

Similar pair of call operators is used here. The question is: do I need line 4 at all? Does the operator defined at line 4 will ever by called? In the following case:

A a(7);
a() = 8;
cout << a() << endl;

always the operator from line 5 is called.

4

2 回答 2

4

是的,将使用第 4 行,例如:

 A a(3);  
 const A b(2);
 a(); // from line 5
 b(); // from line 4
于 2013-08-04T07:02:03.137 回答
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 `_`
};
于 2013-08-04T06:53:46.767 回答