我正在制作一个C++程序来存储员工的数据,如姓名、ID、销售额、佣金金额并计算收入(销售额*佣金)。我正在使用继承的概念。我的基类是“Employee”,派生类是“SeniorEmployee”。当我运行程序时,编译器给出一个错误,指出我无法访问基类的私有成员。错误是这样的
错误:'std::__cxx11::string Employee::name'是私有的。
第二行的另一个错误是
错误:“int Employee::id”是私有的
第三行又出现同样的错误
错误:“double Employee::sales”是私有的
以下是我的代码。我已经包含了所有文件。
文件 Employee.h
#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee(string EmpName, int EmpID, double EmpSales, double EmpComm);
void setName(string EmpName);
string getName();
void setID(int EmpID);
int getID();
void setSales(double EmpSales);
double getSales();
void setComm(double EmpComm);
double getComm();
double earning();
private:
string name;
int id;
double sales;
double commission;
};
#endif
文件 Employee.cpp
#include <iostream>
#include <string>
#include "Employee.h"
using namespace std;
Employee::Employee(string EmpName, int EmpID, double EmpSales, double EmpComm): name(EmpName), id(EmpID), sales(EmpSales), commission(EmpComm)
{
}
void Employee::setName(string EmpName) {
name=EmpName;
}
string Employee::getName() {
return name;
}
void Employee::setID(int EmpID) {
id=EmpID;
}
int Employee::getID() {
return id;
}
void Employee::setSales(double EmpSales) {
sales=EmpSales;
}
double Employee::getSales() {
return sales;
}
void Employee::setComm(double EmpComm) {
commission=EmpComm;
}
double Employee::getComm() {
return commission;
}
double Employee::earning() {
return sales*commission;
}
文件 SeniorEmployee.h
#ifndef SENIOREMPLOYEE_H_
#define SENIOREMPLOYEE_H_
#include "Employee.h"
#include <iostream>
#include <string>
using namespace std;
class SeniorEmployee: public Employee {
public:
SeniorEmployee(string EmpName, int EmpID, double EmpSales, double EmpComm, double BaseSalary);
void setBaseSalary(double BaseSalary);
double getBaseSalary();
private:
double bsalary;
};
#endif
文件 SeniorEmployee.cpp
#include <iostream>
#include <string>
#include "SeniorEmployee.h"
using namespace std;
SeniorEmployee::SeniorEmployee(string EmpName, int EmpID, double EmpSales, double EmpComm, double BaseSalary) : Employee(name,id,sales,commission)
{
}
void SeniorEmployee::setBaseSalary(double BaseSalary) {
bsalary=BaseSalary;
}
double SeniorEmployee::getBaseSalary() {
return bsalary;
}
文件main.cpp
#include <iostream>
#include "SeniorEmployee.h"
using namespace std;
int main() {
string empname = "Fareed Shuja";
int empid = 3978;
double empsales = 30.0;
double empcomm = 0.99;
double basesalary = 50.0;
SeniorEmployee emp(empname,empid,empsales,empcomm,basesalary);
cout << "Name of the Employee is : " << emp.getName() << endl;
cout << "Employee ID is : " << emp.getID() << endl;
cout << "Sale Amount is : " << emp.getSales() << endl;
cout << "Commission is : " << emp.getComm() << endl;
cout << "Earning is : " << emp.earning() << endl;
cout << "Employee's base salary is " << emp.getBaseSalary() << endl;
return 0;
}
为了抗议 OpenAI 交易而删除。