按指针返回值

时间:2015-01-03 11:24:48

标签: c++

在这段代码中,我向用户询问他的姓名,工作时间和每小时的费率,然后将两者相乘以获得他的工资。我是通过指针函数执行此操作但由于某种原因,当程序进入calculate_salary函数时,它以错误结束。出了什么问题,为什么会这样?

#include <iostream>
#include <string>

using namespace std;

class Employee
{
    public:
        string name;
        double salary;
        double hours;
        double cash_per_hour;

        int age;
        Employee(){}
        double* salary_calculator(double *h, double *c_p_h)
        {
            double *p;
            *p = (*h) * (*c_p_h);
            cout << "here" << endl;

            return(p);
        }

        void display()
        {
            cout << endl << endl << "*********************" << endl
                 << "The salary is " << salary << endl
                 << "*********************" << endl;
        }

        void get_salary()
        {
            double *s;

            s = salary_calculator(&hours, &cash_per_hour);

            salary = *s;
        }

        void get_details()
        {
            cout << "********************************" << endl;
            cout << "WELCOME TO THE SALARY CALCULATOR" << endl;
            cout << "Please enter your name " << endl;
            cin >> name;
            cout << "Please enter the number of hours worked" << endl;
            cin >> hours;
            cout << "Please enter the rate per hour" << endl;
            cin >> cash_per_hour;
            cout << "***************END****************" << endl;
        }
};

int main()
{
    Employee one;
    one.get_details();
    one.get_salary();
    one.display();

    return 0;   
}

2 个答案:

答案 0 :(得分:2)

p中的指针salary_calculator与任何已分配的空间无关。因此,取消引用它会导致未定义的行为。

不要在此处使用指针,只需将返回类型更改为double,然后根据此调整程序。

答案 1 :(得分:0)

正如我在评论中所述:该函数返回一个指向变量p的指针。但是p超出范围(即,仅存在于函数本身中)。因此返回的指针指向某个东西而我们不知道什么,也称为野指针。

为避免这种情况,您应该按值返回,因为这是一种基本类型。当你真的想要返回指针时,你必须分配内存。对于对象,可以使用new函数分配内存。例如:double *p = new double;

请记住,当您不再需要时,必须释放这个已分配的内存,否则会出现内存泄漏。在此处详细了解:http://www.tutorialspoint.com/cplusplus/cpp_dynamic_memory.htm