我想知道是否可以通过使用常量引用变量来绕过使用getter方法,具体如下:
#include <string>
class cTest
{
private:
int m_i;
std::string m_str;
public:
const int & i;
const std::string & str;
cTest(void)
: i(m_i)
, str(m_str)
{}
};
int main(int argc, char *argv[])
{
cTest o;
int i = o.i; // works
o.i += 5; // fails
o.str.clear(); // fails
return 0;
}
我想知道为什么人们似乎根本不这样做。我是否遗漏了一些严重的缺点?请为优缺点列表做出贡献,如有必要,请进行更正。
优点:
- 没有通过getter函数调用产生的开销。
- 程序大小减小,因为有较少的函数。
- 我仍然可以修改类的内部,引用变量提供了一层抽象。
缺点:
- 与使用getter函数相比,我有一堆引用。这会增加对象大小。
- 使用
const_cast
,人们可以弄乱私有成员,但这些人是淘气的吧?