see: http://stackoverflow.com/questions/2184133/prevent-class-inheritance-in-c
倾向于使用private constructor and non-virtual destructor.
#include <iostream>
using namespace std;
class CBase
{
public:
static CBase* CreateInstance()
{
CBase* b1 = new CBase();
return b1;
}
private:
CBase() { }
CBase(const CBase &c) { }
CBase& operator=(const CBase &c) { }
};
class CC : public CBase
{
};
int main()
{
CC c;
return 0;
}编译:
/home/a/j/nomad2:g++ Y.CPP
Y.CPP: In constructor 'CC::CC()':
Y.CPP:13: error: 'CBase::CBase()' is private
Y.CPP:19: error: within this context
Y.CPP: In function 'int main()':
Y.CPP:24: note: synthesized method 'CC::CC()' first required here
本文深入分析了C++中类继承时遇到的限制,特别是关于使用private构造函数和非虚拟析构函数的策略。通过实例代码演示,详细解释了如何在类的构造函数和析构函数中应用private修饰符来防止类继承,并提供了相关编译错误的解决思路。
2151

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



