一 如何实现一个不能被继承的类
1.类的构造函数给成私有的。
2.并且在父类中给一个静态的函数构造对象
原因:1.保证了父类的构造函数在子类不可见,但是子类的构造函数是要调用父类的构造函数来合成。
2.但是此时出现了一个问题,把这个类的构造函数弄成私有的,虽然子类不能构造出对象,但是这个类也不能构造出对象了 因此提供一个静态的公有函数来构造对象
#include<iostream>
using namespace std;
class father
{
public:
/*static father GetObj()
{
return father();
}*/
static father* GetObj()
{
return new father;
}
private:
father()
{}
private:
int _num;
};
class child :public father
{
private:
int _a;
};
int main()
{
//father f = father::GetObj();
father * fptr = father::GetObj();
//child c;
system("pause");
return 0;
}
二 实现一个只能在堆上生成对象的类
这个题是让你实现一个只能在堆上生成的类,首先我们要明白在哪儿都能生成对象呢?
1.栈上可以生成对象(father f) 2 堆上可以生成对象 3静态区 定义一个全局对象father f
这时你肯定会不假思索的给了如下代码:
1.把构造函数给成私有的
2.给一个静态函数获取一个对象 (这个对象空间是new出来的)
class father
{
public:
static father* Getobj()
{
return new father();
}
public:
int _num;
private:
father()
{};
};
那我只能说这个你这个不对,因为有可能你在外面构造了一个在堆上生成的对象,但是你有用这个对象拷贝构造了一个对象。这个对象确是在栈上生成的。那如何解决呢?
在上面的基础上把拷贝构造函数和赋值运算符的重载只声明不实现,并且声明为私有的。这就不会用类里面默认的。
类的防拷贝的实现:
1.只声明不实现
2.声明成私有的
三 实现一个只能在栈上生成对象的类
方法一 整体思路:1.把构造函数给成私有的 2.提供一个静态的函数生成一个匿名对象
class father
{
public:
static father Getobj()
{
return father();
}
private:
father()
{};
};
int main()
{
//father* ptr = father::Getobj();
father f = father::Getobj();
system("pause");
return 0;
}
在其他地方也有一种实现方法
方法二
class father
{
private:
void* operator new(size_t size);
void operator delete(void * p);
private:
int _num;
};
class child :public father
{
private:
int _a;
};
我来解释下,要知道要实现一个在栈上生成对象的类,就要求这个类不能再堆上生成对象
而在堆上生成对象就要调用new //而new生成对象 要调用operator new+构造函数 前面阻止在堆上生成对象是在构造函数上下手。而此处是从operator new上下手。但是这种方法有一个缺陷就是尽管你防止了在堆上生成对象,但是你不能保证它是在栈上生成的对象。应为你这样有可能实在静态区上创建的。