问题描述
当我在子类“Manager”中声明构造函数时,我认为我做错了什么。 不明白是不是两个类之间的继承问题。
员工.h
#ifndef EMP_IMP_H_INCLUDED
#define EMP_IMP_H_INCLUDED
#include<string>
using namespace std;
class Employee
{
private:
string name;
int salary;
public:
Employee(string n,int s){name=n; salary=s;};
virtual ~Employee() {}
//GetName();
//GetSalary();
//virtual PrintInfo();
};
class Manager:public Employee
{
private:
int bonus;
public:
Manager(string n,int s,int b){name=n;salary=s;bonus=b;};
virtual ~Manager() {};
//GetBonus();
//PrintInfo();
};
#endif // EMP_IMP_H_INCLUDED
main.cpp
#include <iostream>
#include <string>
#include "Nodo.h"
#include "EMP_IMP.h"
using namespace std;
int main(){
Employee *emp1=new Employee (string("ciro esposito",1000));
Employee *emp2=new Employee(string("Gennaro Espostio"),2000);
Employee *emp3=new Manager(string("Carmine Espostio"),2000,2000);
Employee *emp4=new Manager(string("Salvatore Espostio"),3000,3000);
}
解决方法
class Manager
的构造函数必须将 n
和 s
参数传递给基类构造函数,而不是直接初始化基类数据成员。此外,虽然在构造函数体中赋值 bonus = b;
是有效的,但最好也将它放在初始化列表中:
Manager(string n,int s,int b) : Employee(n,s),bonus(b){}