C++中私有继承公有化

当私有继承时,基类的所有public成员都变成了private。如果希望它们中的任何一个 是可视的,只要用派生类的public部分声明它们的名字即可:

#include<iostream>
using namespace std;

class Pet {
public:
char eat() const {return 'a';}
int speak() const {return 2;}
float sleep() const {return 3.0;}
float sleep(int) const {return 4.0;}
};

class Goldfish : Pet {
public:
using Pet::eat;
using Pet::sleep;
using Pet::speak;
};

int main(){
Goldfish bob;
cout << bob.eat() <<'\n';
cout << bob.sleep()<<'\n';
cout << bob.sleep(1) <<'\n';
cout << bob.speak();
}

 

posted @ 2021-01-26 22:03  诗和远方*  阅读(136)  评论(0编辑  收藏  举报