鱼生富贵 2022-12-29 20:16 采纳率: 97.4%
浏览 18
已结题

关于#c++#的问题:想知道为什么在Manage类的成员函数里使用Employee类的私有成员数据会报错呢

题目是这样的:

img


我写的是下面这样的,想知道为什么在Manage类的成员函数里使用Employee类的私有成员数据会报错呢?哪里不对吗


#include<iostream>
using namespace std;

class Employee {
private:
    //1)
    string name;
    float salary;
public:
    Employee(const string new_name, float new_salary = 10000);//1.1)
    Employee(Employee& emp);//1.2)
    void raiseSalary(float percent);//1.3)
    void show();//1.4)
    //1.5)
    string getName() const
    {
        return name;
    }
    float getSalary() const
    {
        return salary;
    }
};

//1.1)
Employee::Employee(const string new_name, float new_salary):name(new_name),salary(new_salary)
{}
//1.2)
Employee::Employee(Employee& emp):name(emp.name),salary(emp.salary)
{}
//1.3)
void Employee::raiseSalary(float percent)
{
    salary = salary * (1 + percent);
}
//1.4)
void Employee::show()
{
    cout << "His or Her name is:" << name << endl;
    cout << "the salary of this employee:" << salary << endl;
}

class Manager:public Employee {
private:
    //2)
    string position;
    float bonus;
    Employee emplo;
public:
    Manager(const string &new_name, string position, float bonus = 0.1, float new_salary=20000);//2.1)
    //2.2)为新添加的成员编写合适的访问函数
    string getPosition() const
    {
        return position;
    }
    float getBonus() const
    {
        return bonus;
    }
    void raiseSalary(float percent);//2.3)
    void show();//2.4)
};

//2.1)
Manager::Manager(const string& new_name, string position, float bonus, float new_salary):Employee(new_name,new_salary),position(position),bonus(bonus)
{}
//2.3)
void Manager::raiseSalary(float percent)
{
    salary = salary * (1 + percent + bonus);
}
//2.4)
void Manager::show()
{
    cout << "His or Her name is:" << name << endl;
    cout << "Employee Type: Manager," << " Name = " << name << " ,Position = " << position << " ,Salary =" << salary << endl;
    cout << "the salary of this employee:" << salary << endl;
}

int main() {
    Employee tom("Tom");
    tom.show();
    tom.raiseSalary(0.1);
    tom.show();
    Manager ceo("Peter", "CEO", 30000, 0.1);
    ceo.show();
    ceo.raiseSalary(0.15);
    ceo.show();
    return 0;
}
  • 写回答

1条回答 默认 最新

  • cjh4312 2022-12-29 21:11
    关注

    子类是不能访问父类的私有变量的,加了public也不行,除非父类有共有函数操作私有变量

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 1月10日
  • 已采纳回答 1月2日
  • 创建了问题 12月29日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分