访问方法C++时出现问题

stuck accessing a method C++

本文关键字:问题 方法 C++ 访问      更新时间:2023-10-16

我正在尝试重新创建一个收银机程序。我有一个员工对象,它有一个名称和折扣%

staffMember me ("tom", 20);

我想把折扣加到收银台的总额上。如果我像这样使用me.getDiscountPercent将折扣作为整数参数传递,我的方法就会起作用

cashy.applyStaffDiscount(me.getDiscountPercent());
void cashRegister::applyStaffDiscount(int discount){
    total = (total/100)*(100-discount);
}

然而,我想记住员工的名字,这样我就可以有不同折扣的员工。我做了这个不起作用

string employee;
cout << "Enter name: ";
cin >> employee;
cashy.applyStaffDiscount(employee);

方法:

void cashRegister::applyStaffDiscount(string employee){
total = (total/100)*(100-employee.getDiscountPercent());
}

感谢Tom

参数employeestd::string,而不是staffMember。在你的applyStaffDiscount函数中,你必须传递一个员工,而不是一个字符串:

string employee_name;
int employee_discount;
cout << "Enter employee data: ";
cin >> employee_name;
cin >> employee_discount;
staffMember employee( employee_name , employee_discount); //Staff variable
cashy.applyStaffDiscount(employee);
/* ... */
void cashRegister::applyStaffDiscount(const staffMember& employee)
{
    total = (total/100)*(100-employee.getDiscountPercent());
}

employee的数据类型为字符串。string类(来自std命名空间)没有任何名称为getDiscountPercent()的方法。也许,你想做的是:

string name;
int discount;
cout << "Enter name: ";
cin >> name;
cout << "Enter discount: ";
cin >> discount;
staffMember employee (name, discount); // <-- this is what you really want!
cashy.applyStaffDiscount(employee);