如何将一个方法中的值返回到同一个类的另一个方法

时间:2018-01-31 14:28:11

标签: c++ return-value

我有两个代码示例Employee.hEmployee.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()中的返回值(工资)?

2 个答案:

答案 0 :(得分:3)

答案是使用this将值赋给实例变量而不是临时变量:

double Employee::calcNetSalary(double basicSalary,double othrs, double otrate){
    salary=(basicSalary+othrs*otrate);   
    return salary;
}

答案 1 :(得分:0)

您正在为calcNetSalary函数中的局部变量赋值。将值分配给您的私有成员变量薪水

另一种选择是在displayNetSalary函数中调用calcNetSalary