我有基类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
}
答案 0 :(得分:1)
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
}
这里初始化基类中定义的成员ID,名称,工资和许可。您需要将它传递给基类构造函数进行初始化。你不能直接初始化它们
id
,name
和clearance
受到保护,因此您可以在派生类中访问它们,但不能使用初始化列表直接初始化它们。您可以initialize inside the constructor
或make a call to base constructor in initialization list
。
Worker::Worker(std::string t_id, std::string t_name, float wage, int num):Manager(t_id,t_name,wage,0), projects (num)
{
//ctor
}
答案 1 :(得分:0)
派生类不会看到其基类的私有成员。你必须委托构造函数。
答案 2 :(得分:0)
您的Worker
构造函数应该是:
Worker::Worker() : Manager("w000000", " - ", 0, 0) {}
Worker::Worker(std::string t_id, std::string t_name, float wage, int num) :
Manager(t_id, t_name, wage, num)
{
}