0

这是一个错误吗?我认为私有成员不是从基类继承的:

“HourlyEmployee类的定义没有提到成员变量name、ssn、netPay,但是HourlyEmployee类的每个对象都有成员变量name、ssn、netPay。成员变量name、ssn、netPay继承自类雇员。”

 //This is the header file hourlyemployee.h.
 //This is the interface for the class HourlyEmployee.
 #ifndef HOURLYEMPLOYEE_H
 #define HOURLYEMPLOYEE_H

 #include <string>
 #include "employee.h"
 using std::string;


namespace SavitchEmployees
{
class HourlyEmployee : public Employee
{
public:
    HourlyEmployee( );
    HourlyEmployee(const string& theName, const string& theSsn,
    double theWageRate, double theHours);
    void setRate(double newWageRate);
    double getRate( ) const;
    void setHours(double hoursWorked);
    double getHours( ) const;
    void printCheck( );
private:
    double wageRate;
    double hours;
};
 }//SavitchEmployees
 #endif //HOURLYEMPLOYEE_H

其他头文件:

//This is the header file employee.h.
//This is the interface for the class Employee.
//This is primarily intended to be used as a base class to derive
//classes for different kinds of employees.
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>

using std::string;

namespace SavitchEmployees
{
    class Employee
    {
    public:
        Employee( );
        Employee(const string& theName, const string& theSsn);
        string getName( ) const;
        string getSsn( ) const;
        double getNetPay( ) const;
        void setName(const string& newName);
        void setSsn(const string& newSsn);
        void setNetPay(double newNetPay);
        void printCheck( ) const;
    private:
        string name;
        string ssn;
        double netPay;
    };
}//SavitchEmployees

#endif //EMPLOYEE_H
4

4 回答 4

3

所有成员都由子类继承。如果它们是私有的,则无法(直接)访问它们。它们仍然可以通过调用公共方法(例如setName.

于 2012-12-16T21:02:48.957 回答
2

私有成员存在于子类中,但在大多数情况下不可访问。只有基类中的函数才能触及它们,没有friend声明或字节级黑客。

于 2012-12-16T21:02:38.917 回答
2

报价是正确的。所有数据成员,无论是否私有,都由派生类继承。这意味着每个派生类的每个实例都包含它们。但是,派生类不能直接访问私有成员。

但是,您可以通过公共或受保护的访问器访问此类成员,例如getName().

于 2012-12-16T21:02:47.463 回答
-1

为此,您拥有受保护的访问级别。所以使用受保护的而不是私有的。

于 2012-12-16T21:04:40.910 回答