我有基類Manager
和派生類Worker
,繼承似乎正常工作 - 我創建了派生類的新對象,使用它的默認構造函數,我可以正確輸出。 但現在我想爲派生類(Worker
)做一個重載的構造函數,似乎有一個編譯錯誤,我厭倦了尋找答案,但我沒有找到答案。 爲什麼編譯說Worker
沒有ID,名稱和薪水字段?我在書中創建了一個派生類,併爲它創建了ctors。派生類中的重載構造函數
Manager
頭:
#include <string>
#ifndef MANAGER_H
#define MANAGER_H
class Manager
{
public:
Manager(); //ctor
Manager (std::string, std::string, float, int); //overloaded ctor
friend void display (Manager&); //friend function is declared
~Manager(); //dtor
protected:
std::string id;
std::string name;
float salary;
private:
int clearance;
};
Manager
CPP:
#include <iostream>
#include "Manager.h"
#include "Worker.h"
Manager::Manager() //default ctor
{
id = "M000000";
name = "blank";
salary = 0;
clearance = 0;
}
Manager::Manager(std::string t_id, std::string t_name, float wage, int num): id (t_id), name (t_name), salary(wage), clearance (num)
{
//overloaded ctor
}
Manager::~Manager()
{
//dtor
}
Worker
頭:
#include <string>
#ifndef Worker_H
#define Worker_H
class Worker: public Manager
{
public:
Worker();
Worker (std::string, std::string, float, int);
~Worker();
friend void display (Worker&); //friend function is declared
protected:
int projects;
private:
};
#endif // Worker_H
Worker
CPP:
#include <iostream>
#include "Manager.h"
#include "Worker.h"
Worker::Worker() //default ctor
{
id = "w000000";
name = " - ";
salary = 0;
projects = 0;
}
Worker::Worker(std::string t_id, std::string t_name, float wage, int num) : id (t_id), name (t_name), salary (wage), projects (num);
{
//ctor
}
Worker::~Worker()
{
//dtor
}
類應該負責初始化自己的成員。委託給一個'Manager'構造函數。 – chris
爲什麼Worker的構造函數在其初始化列表中調用Manager的構造函數? –
不是你的問題的主題,但你的模型似乎不適合繼承。按照你的計劃,任何工人都是經理(工人可以在任何地方使用,而不是經理),這是不正確的。 – bolov