逻辑错误 - 派生类不将变量传递给父函数

时间:2015-05-13 05:50:52

标签: c++ inheritance

当我运行此代码时,名称和工资变量永远不会使用派生类" Programmer"设置,即使它通过父类传递变量'建议的here构造函数。没有给出任何错误,但名称和工资变量似乎因某种原因而无法设定。

#include <string>
#include <iostream>


using namespace std;


class Employee 
{
public:
   Employee();
   Employee(string employee_name, double initial_salary);

   void set_salary(double new_salary);
   double get_salary() const;
   string get_name() const;
private:
   string name;
   double salary;
};


Employee::Employee()
{  
   salary = 0;
}

Employee::Employee(string employee_name, double initial_salary)
{  
   name = employee_name;
   salary = initial_salary;
}

void Employee::set_salary(double new_salary)
{  
   salary = new_salary;
}

double Employee::get_salary() const
{  
   return salary;
}

string Employee::get_name() const
{  
   return name;
}

class Programmer : public Employee {
public:
    Programmer(string name, double salary);
    string get_name();
private:
};

Programmer::Programmer(string pname, double psalary)
{
    Employee(pname, psalary);
}

string Programmer::get_name()
{
    return Employee::get_name();
}

int main() {
    Programmer harry("Hacker, Harry", 10000);
    cout << harry.get_name();
    return 0;
}

This question与我能说的问题不一样。虽然那个更复杂。

这似乎是一个简单的逻辑错误,我无法找到它。

2 个答案:

答案 0 :(得分:0)

您必须使用成员初始值设定项列表来启动基类。使用构造函数,您可以在函数体中创建一个临时的Employee。

Programmer::Programmer(string pname, double psalary)
  : Employee(pname, psalary)  
{}

答案 1 :(得分:0)

Programmer::Programmer(string pname, double psalary)
{
    Employee(pname, psalary);
}

相当于:

Programmer::Programmer(string pname, double psalary) :
   Employee()
   // Base class is initialized using the default constructor.
{
    Employee(pname, psalary);
    // Create a temporary Employee and discard it.
}

要传递namepsalary来初始化基类,您需要使用:

Programmer::Programmer(string pname, double psalary) :
   Employee(pname, psalary)
   // Base class is initialized using the constructor
   // that takes name and salary as arguments.
{
}