设计一个不能被继承的类

在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

不过这个问题的实用性不强,在实际并没有什么用途,只为考查继承

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值