如何设计一个不能被继承的类 (C++)
思路:
子类的继承过程中哪些会和父类产生关系呢?
#include<iostream>
using namespace std;
class A
{
public:
A() {
cout << "A()" << endl;
}
~A() {
cout << "~A()" << endl;
}
};
class B :public A
{
public:
B() {
cout << "B()" << endl;
}
~B() {
cout << "~B()" << endl;
}
};
int main()
{
B b;
return 0;
}

依次执行A的构造,B的构造,B的析构,A的析构
那么我们只要让子类B不能正常调用父类A的构造函数就可以,该如何实现?
//会报错,不能运行
#include<iostream>
using namespace std;
class A
{
private: //更改处
A() {
cout << "A()" << endl;
}
~A() {
cout << "~A()" << endl;
}
};
class B :public A
{
public:
B() {
cout << "B()" << endl;
}
~B() {
cout << "~B()" << endl;
}
};
int main()
{
A a;
B b;
return 0;
}
如果我们进行了如下更改,发现该程序根本不能运行。因为我们设计的类不仅不能被继承,还不能创建对象,一个类如果不能创建对象也不能被继承那存在的意义就没有。
如果我们能让父类A能创建对象就行,想到了静态函数。毕竟静态函数既属于类,也属于对象,但最终属于类。接下来单独在父类A中设计静态成员函数,让类A能创建对象。
#include<iostream>
using namespace std;
class A
{
private:
A() {
cout << "A()" << endl;
}
public:
~A() {
cout << "~A()" << endl;
}
public:
static A &constructor() {
A a;
return a;
}
};
class B :public A
{
/*这几行不屏蔽,编译时会报错,因为子类构造函数和析构函数会调用父类的构造函数和析构函数,而此时父类的构造函数和析构函数已经是private,对子类不可见*/
//public:
//B() {
// cout << "B()" << endl;
//}
//~B() {
// cout << "~B()" << endl;
//}
};
int main()
{
A aa=A::constructor();
//B b;
return 0;
}
这样设计的类就不能被继承,但平时我们设计的类中构造函数和和析构函数访问修饰符是一样的,我们可以再改进一下。上面的例子在栈中创建A的对象,接下来可以在堆中创建A的对象。
#include<iostream>
using namespace std;
class A
{
private:
A() {
cout << "A()" << endl;
}
~A() {
cout << "~A()" << endl;
}
public:
static A *constructor() {
A *a=new A();
return a;
}
static void destructor(A* a) {
delete a;
}
};
class B :public A
{
//public:
//B() {
// cout << "B()" << endl;
//}
//~B() {
// cout << "~B()" << endl;
//}
};
int main()
{
A *aa=A::constructor();
A::destructor(aa);
//B b;
return 0;
}
本文探讨了如何在C++中设计一个不能被继承的类,通过阻止子类调用父类构造函数实现这一目标。作者指出,通过使用静态成员函数来创建对象,可以确保类既能创建实例又无法被继承。
13万+

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



