在c++中每个类都一个构造函数和一个析构函数,即使用户不明确定义,系统也会类定义一个默认的构造函数和析构函数。当创建该类的对象可以显示或者隐式调用构造函数,当对象销毁时会自动调用析构函数。
当有子类继承父类,创建子类的对象时,会自动调用父类的构造函数,同样当对象销毁时也会自动调用父类的析构函数。
在类属性中private不允许用户和子类调用该函数的方法。
因此要想使用得类不能被继承,可以将构造函数和析构函数声明成private,这样在编译阶段编译器会给出继承失败
- class Parent{
- private:
- Parent(){};
- ~Parent(){};
- };
- class Child : public Parent
- {
- };
- int main()
- {
- Child object;
- return 0;
- }
~
lab623c@lab623c-desktop:~/realxie/cpp$ g++ Parent.cpp -o parent
Parent.cpp: In constructor 'Child::Child()':
Parent.cpp:3: error: 'Parent::Parent()' is private
Parent.cpp:8: error: within this context
Parent.cpp:4: error: 'Parent::~Parent()' is private
Parent.cpp:8: error: within this context
Parent.cpp: In function 'int main()':
Parent.cpp:13: note: synthesized method 'Child::Child()' first required here
Parent.cpp: In destructor 'Child::~Child()':
Parent.cpp:4: error: 'Parent::~Parent()' is private
Parent.cpp:8: error: within this context
Parent.cpp: In function 'int main()':
Parent.cpp:13: note: synthesized method 'Child::~Child()' first required here
不过这个问题的实用性不强,在实际并没有什么用途,只为考查继承