解析:今天在看Effective C++时,看到了抽象函数详解那块,于是很自然的就想到了以前看过的一道题:创建只在堆上生成的变量。这题换句话说:只能用指针创建变量,即Type *value=get_point();类似于这样的问题,
有两种方法可以完成这个问题:
1、第一种,也是最能先想到的一种,将构造函数放在private(私有)里,这样就无法在栈上定义变量了,这种很简单,基本学过class的程序员都能想到,现在要不构造函数不能设置成私有的,该怎么解决,那么你接下来看我第二种实现就很有意义了
2、用抽象类实现,一般的书上都是这样写的,抽象类如果不用在继承里的话就没多大意义,而我现在就要推翻这个说法,准确的来说的抽象类一般都用在继承中才能体现它的价值,将方法重新实现,即只为子类提供一个接口而不提供实现方法,这就是抽象类存在的价值,
ps 注意:两个得到对象地址都需要使用static修饰
#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;
//使用抽象类实现
class base
{
public:
void virtual show()const=0;
//必须定义成静态的,因为它需要支持::这样访问
static base *GetPoint()
{
//可以使用C语言中malloc函数来实现内存分配
base *tmp=(base*)malloc(sizeof(base));
assert(tmp !=NULL);
//这不能使用new来分配空间,因为是抽象类
//base *tmp=new base;
return tmp;
}
void fun()const
{
cout<<"base fun"<<endl;
}
};
//将构造函数定义成私有的
class trans_base
{
private:
trans_base()
{}
public:
//必须定义成静态的,因为它需要支持::这样访问
static trans_base* GetBase()
{
//1、可以用两种方式申请空间,new或者malloc
//trans_base *tmp=new trans_base;
//2、用malloc申请空间也是可以的
trans_base *tmp=(trans_base*)malloc(sizeof(trans_base));
assert(tmp !=NULL);
return tmp;
}
void show()const
{
cout<<"trans_base show"<<endl;
}
};
void test()
{
//base bs;//error
base *pbs=base::GetPoint();
pbs->fun();
//trans_base tb; //error
trans_base *ptb=trans_base::GetBase();
ptb->show();
}