不能被继承的类

方法一:通过私有化构造函数

代码:

#include <iostream>

using namespace std;

//只能在堆上进行创建
class sealedClass{
private :
	sealedClass(){}
	~sealedClass(){}

public:
	static sealedClass * getInstance(){
		return new sealedClass();
	}
	static void deleteInstance(sealedClass *pInstance ){
		delete pInstance;
	}
};


void main(){

   sealedClass *pinstance =	sealedClass::getInstance();
   sealedClass::deleteInstance(pinstance);
}

方法二:

通过虚继承和模板

#include <iostream>

using namespace std;

template<typename T> class makeClass{
	public :
		friend T;
private :
	makeClass(){}
	~makeClass(){}
};


//可移植性差
class sealedClass : virtual  public makeClass<sealedClass> {
public:
	sealedClass(){}
	~sealedClass(){}
};
/*
class Try2 : public sealedClass
{	
	Try2(){}
	~Try2(){}
	
};
*/

void main(){

}


你可能感兴趣的:(不能被继承的类)