C++ 继承 二

123 阅读1分钟

C++隐藏

父子关系,成员同名,才能隐藏

#include <iostream>
#include <cstdlib>

using namespace std;


//.h
class Person {
public:
    void eat();

protected:
    string m_strName;
    int m_iAge;
private:
    string test;
};

class Worker : public Person {
public:
    void eat();
    int m_iSalary;
protected:
    string m_strName;
private:
};


//cpp  这叫定义
void Person::eat() {
    cout<<"Person::eat()"<<endl;

}
void Worker::eat() {
    Person::m_strName="kitty"; //访问父类的隐藏成员
    cout<<"Worker::eat()"<<endl;
    cout<<Person::m_strName<<endl;
}

int main() {
    Person p;
    p.eat();
    Worker w;
    w.Person::eat();//访问父类的隐藏函数
    w.eat();
    return 0;
}

C++多继承