Effective C++(审慎的使用private继承)


author:

  • luixiao1223
    title: 审慎的使用private继承

private

class Person{};
class Student:private Person{};// 使用私有继承时,基类的所有函数都会变成派生类的私有函数。基类的私有,派生类是无法访问的。
void eat(const Person& p);
void study(const Student& s);

Person p;
Student s;
eat(p);
eat(s); // 错误

private继承再软件设计上没有意义。只是实现上有意义。也就是你实际上是用到了基类中的一些功能,仅此而已。它不是一个is
a关系。

激进情况迫使你使用private继承

为了让空间最小化。只适用于空的类,也就是不含non-static成员变量,没有virtual函数也没有virtual
base classes的类。

class Empty{};
class HoldsAnInt{
private:
    int x;
    Empty e;
};

// sizeof(HoldsAnInt) > sizeof(int)

class HoldsAnInt:private Empty{
private:
    int x;
};

//sizeof(HoldsAnInt) == sizeof(int)

tips

尽量使用has
a关系。也就是说尽量使用复合而不要使用private继承。无论什么时候,只要可以,使用has
a关系。

end

  1. 当derived class需要访问protected base
    classs的成员,或需要重新定义继承而来的virtual函数时,可以考虑使用private
  2. 当需要让class尺寸最小化时考虑使用private
    加粗样式
发布了127 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/luixiao1220/article/details/104022853