引用代替getter? [英] Reference in place of getters?

查看:120
本文介绍了引用代替getter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<$> p $ p> class X
{
int mP;
public:
const int& P;
X():P(mP){}
};

及更高版本

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

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



Having'const int& x'发布私有成员将工作:

  class X {
private:int m_x;
public:const int& X;
public:X():m_x(0),x(m_x){}
//注意复制和赋值
};

成本是更大的内存占用。


in C++ is it a bad practice to use reference in place of getters?

for example:

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

and later

X xl;
int h = xl.P;

解决方案

None of this is good:

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

Pick one, it's a design decision.

Having 'const int& x' to publish the private member will work:

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

The cost is a larger memory footprint.

这篇关于引用代替getter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆