创建一个不能被继承的类
法一:
要创建一个不能被继承的类,我们容易想到的方法是:将构造函数私有化,重新编写create()函数,创建对象,同时为了对称可以将析构函数也私有化,重新编写destory()。
class Base
{
public:
static Base* Create(int b)
{
Base* ba = new Base;
ba->_b = b;
return ba;
}
static void Destory(Base* ba)
{
delete ba;
ba = NULL;
}
private:
Base()
{}
~Base()
{}
public:
int _b;
};
void ForFun()
{
Base* ba = Base::Create(2);
cout<<ba->_b<<endl;
Base::Destory(ba);
}
Base可以被调用。显示打印2
定义一个类,继承Base。
class Better:public Base
{
public:
Better()
{}
~Better()
{}
};
void ForFun()
{
Better bt;
Better* bt2 = new Better;
}
对于这种方法,父类创建对象只能在堆上创建,不能在栈上创建。
法二:
(1)在基类中定义一个友元类,设置为模板(模板为子类);
(2)将构造函数与析构函数设置为私有;
(3)子类虚拟继承父类;
(4)调用子类创建对象,可以在堆上或栈上创建对象;
(5)定义子类2继承子类,该子类2不能创建对象。
不能被继承的类是—>Better。
static Base* Create(int b)
{
Base* ba = new Base;
ba->_b = b;
return ba;
}
static void Destory(Base* ba)
{
delete ba;
ba = NULL;
}
private:
Base()
{}
~Base()
{}
public:
int _b;
};
class Better:virtual public Base<Better>
{
public:
Better()
{}
~Better()
{}
};
class Final:public Better
{
public:
Final()
{}
~Final()
{}
};
void ForFun()
{
Better *b = new Better; //堆上对象
Better bt; //栈上对象
}
只能在堆上创建对象
动态建立:使用new运算符将对象建立在对空间中。
A* a = new A;
执行过程:
(1)执行operator new()函数,在堆空间中搜索合适的内存并进行分配;
(2)调用构造函数构造对象,并初始化内存空间。
法一:将构造函数设为私有。
确实不能在栈上创建对象了,但同时也不能再堆上创建对象了。
不可取。
法二:将析构函数设为私有,编写destory()函数释放空间。
问题:该类同时无法作为基类被继承。
解决方法:
(1)将析构函数设为virtual(虚函数),在子类中重写析构函数。
(2)将析构函数设为protected,类外无法访问,但子类可以访问。
可以在堆上创建空间:
不能在栈上创建空间:
![]()
法三:将构造函数与析构函数设为protected,编写create()和destory()。
可以使用函数来进行创建与删除。
只能在栈上创建对象
由编译器为对象在栈上分配内存空间。
执行步骤:直接调用构造函数。
因为在堆上创建对象需要调用new,所以讲operator new设置为私有的即可。