引用代替吸气剂?

Shubham

在C ++中,使用引用代替吸气剂是一种不好的做法吗?

例如:

class X
{
    int mP;
 public:
    const int& P;
    X():P(mP){}
}; 

然后

X xl;
int h = xl.P;
用户名

这些都不是好事:

class X { public: int x; };
class X {
    private: int m_x;
    public: const int& get() const { return m_x; }
    public: void set(const int& other)  { m_x = other; } 
};
class X {
    private: int m_x;
    public: const int& x() const { return m_x; }
    public: void x(const int& other)  { m_x = other; } 
};
class X {
    private: int m_x;
    public: const int& x() const { return m_x; }
    public: int& x()  { return m_x; }
};

选择一个,这是一个设计决定。

具有“ const int&x”来发布私有成员将起作用:

class X {
    private: int m_x;
    public: const int& x;
    public: X() : m_x(0), x(m_x) {}
    // Take care for copy and assignment
};

代价是更大的内存空间。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章