c++有太多的trick,下面是一个实例,代码如下:
class Father
{
public:
Father()
:count(0) {cout << "father create " << ++count << " times!" << endl;}
~Father() {cout << "father destory!" << endl;}
protected:
int count;
};
class Son : public Father
{
public:
Son(int i)
: Father(), ival(i)
{cout << "son create " << count << " times" << endl;
cout << ival << endl;}
~Son()
{
cout << "son destory!" << endl;
}
private:
const int& ival;
};
i

本文展示了C++中一种利用构造函数重载使类内部成员只读,外部可修改的技巧。通过示例代码解释了如何在类`Father`和其子类`Son`中实现这一效果,并探讨了该技巧的实际应用价值,提醒读者这只是对C++理解的一种深入方式,参考自《Effective C++》条款12。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



