我有两个代码示例Employee.h
和Employee.cpp
Employee.h
如下:
#include<iostream>
using namespace std;
#define SIZE 20
class Employee{
private:
double othrs, otrate,salary;
protected:
int Empno;
char name[SIZE];
int telephone;
double basicSalary;
public:
Employee();
~Employee();
double calcNetSalary(double basicSalary,double othrs, double otrate);
void displayNetSalary();
};
这是Employee.cpp
#include<iostream>
#include "Employee.h"
using namespace std;
Employee::Employee(){
}
Employee::~Employee(){
}
double Employee::calcNetSalary(double basicSalary,double othrs, double otrate){
double salary=(basicSalary+othrs*otrate);
return salary;
}
void Employee::displayNetSalary(){
cout<<"Net Salary : "<<salary; //This line doesn't print the correct value but some other values (**6.01347e-154**)
}
这是Main.cpp
#include<iostream>
#include "Employee.h"
using namespace std;
int main(){
Employee *emp=new Employee();
emp->calcNetSalary(10,20,30);
emp->displayNetSalary();
return 0;
};
有没有办法可以在calcNetSalary(double basicSalary,double othrs, double otrate)
方法中使用displayNetSalary()
中的返回值(工资)?
答案 0 :(得分:3)
答案是使用this将值赋给实例变量而不是临时变量:
double Employee::calcNetSalary(double basicSalary,double othrs, double otrate){
salary=(basicSalary+othrs*otrate);
return salary;
}
答案 1 :(得分:0)
您正在为calcNetSalary函数中的局部变量赋值。将值分配给您的私有成员变量薪水
另一种选择是在displayNetSalary函数中调用calcNetSalary