C++面试题之继承

目录

设计一个类型,不能在外部环境中创建该类的对象

设计一个不能被继承的类

设计一个不能被继承的类 , 但可以在外部环境创建该类型的对象

设计一个能被继承的类 , 但不能在外部环境创建该类型的对象

限制派生类对象不可以拷贝和赋值如何实现。


 

设计一个类型,不能在外部环境中创建该类的对象

class Singleton
{
	int value;
private: // protected:
	Singleton(int x = 0) :value(x) {}
public:
	Singleton(const Singleton&) = delete; // c98;
	Singleton& operator=(const Singleton&) = delete;
private:
	~Singleton() { cout << "~Singleton" << endl; }
public:
	static Singleton& getInstance()
	{
		static Singleton s(10);
		return s;
	}
	//static Singleton sc;
};

0a74e2bbd45e46a183bddbe328a3eca7.png 

 

设计一个不能被继承的类

class non_herit
{
private:
	non_herit() {}
public:
	non_herit(const non_herit&) {}
	~non_herit() {}
};
class B : non_herit
{

};
int main()
{
	//B b;
}

0037806d2b084a5ba915ed456dcf8cfe.png

 

设计一个不能被继承的类 , 但可以在外部环境创建该类型的对象

class non_herit final : public Object
{
	int value;
public:
	non_herit(int x = 0) :value(x) {}
	non_herit(const non_herit&) = default; // delete // c11;
	non_herit& operator=(const non_herit&) = default;
	~non_herit() = default;
};

设计一个能被继承的类 , 但不能在外部环境创建该类型的对象


class Object
{
private:
	int value;
protected:
	Object(int x = 0) :value(x) {}
	Object(const Object& obj) :value(obj.value) {}
	Object& operator=(const Object& obj)
	{
		if (this != &obj)
		{
			value = obj.value;
		}
		return *this;
	}
public:
	~Object() {}
};

限制派生类对象不可以拷贝和赋值如何实现。


class noncopyable
{
public:
	noncopyable() = default;
	~noncopyable() = default;
protected:
	noncopyable(const noncopyable&) = delete;
	noncopyable& operator=(const noncopyable&) = delete;
};                                     

83ddb8fa8d814892a5aabb14a567852f.png

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值