记住:
为防止编译器暗自提供的功能,可将相应的成员函数声明为privae并且不予实现。也可以使用Uncopyable这样的父类实现。
对于独一无二的对象,希望不支持拷贝构造函数和赋值操作符。
class HomeForSale { public: ... private: HomeForSale(const HomeForSale&); //只是声明,阻止编译器自动生成 HomeForSale& operator=(const HomeForSale&); } HomeForSale h1; HomeForSale h2; HomeForSale h3(h1); // 编译失败 h1 = h2; // 编译失败
另一种方法
class Uncopyable { protected: //允许子类对象构造和析构 Uncopyable() {} ~Uncopyable() {} private: Uncopyable(const Uncopyable&); //阻止拷贝 Uncopyable& operator=(const Uncopyable&); } class HomeForSale: private Uncopyable { } HomeForSale h1; HomeForSale h2; HomeForSale h3(h1); // 编译失败 h1 = h2; // 编译失败
基类中 继承方式 子类中
public & public继承 => public
public & protected继承 => protected
public & private继承 = > private
protected & public继承 => protected
protected & protected继承 => protected
protected & private继承 = > private
private & public继承 => 子类无权访问
private & protected继承 => 子类无权访问
private & private继承 = > 子类无权访问
原文地址:https://www.cnblogs.com/pfsi/p/9161585.html
时间: 2024-10-13 16:24:32