通过继承访问受保护的成员

时间:2015-04-29 18:04:14

标签: c++ inheritance

在这段代码中,我试图从派生类访问基类的受保护成员。但在派生类中,它表示"无法访问受保护的成员"

#include<iostream>
using namespace std;

class Employee
{
public:

    Employee(char Name, int perHrPay) { Name_user=Name, PerHr=perHrPay;};
    Employee() {}
    ~Employee() {}
    char getName() const;
    float getPayPerHr() const;
    float paymentIs() const ;

protected:
    char Name_user;
    float PerHr; 
};

class Manager : public Employee
{
public:
    Manager(){}
    ~Manager(){}
    float paymentIs() const ;
};

char Employee::getName() const { return Name_user; }
float Employee::getPayPerHr() const { return PerHr; }
float Employee::paymentIs() const { return PerHr*3; }


int main()
{
    Employee emp('S',94);
    Manager man;
    cout << " The name is " << emp.getName() << endl;
    cout << "The per hr pay is " << emp.getPayPerHr() << endl;
    cout << "The payment is " << emp.paymentIs() << endl;    
    cout << "Name inherited" << man.Name_user << endl;
    cout << "Per hr pay is " << man.PerHr << endl;
    return 1;
}

在此代码中,man无法访问Employee类中的受保护成员Name_user。我不明白为什么继承的类无法访问它。 请帮忙

2 个答案:

答案 0 :(得分:4)

继承类能够访问受保护的成员,但在您的代码中,您尝试从main函数访问它,而不是从派生类方法访问...

答案 1 :(得分:1)

您无法从Name_user中的PerHremp访问manmain()

允许Manager的实施访问Employee的受保护成员。允许用户或Manager使用Employee的公共接口,因为它公开继承自Employee

因此,从man开始,使用访问者方法,就像使用emp一样。

    cout << "Name inherited" << man.getName() << endl;
    cout << "Per hr pay is " << man.getPayPerHr() << endl;