如何编写已继承的大纲构造函数?

How to write outline constructor that has been inheritance?

本文关键字:构造函数 何编写 继承      更新时间:2023-10-16

我正在尝试用c ++编写OUTLINE继承构造函数。 我不确定这是否可能。 我只编写了内联继承构造函数。

如果有办法写,你能分享一下吗?

谢谢。

这是我的代码。

18 public: 
19         FullTimeEmployee(int eid, string name, int salary):Employee(eid, name);
20         int getSalary(){ return salary; }
21 };
22 
23 FullTimeEmployee::FullTimeEmployee(int eid, string name, int salary):Employee(eid, name){
24         this->salary = salary;
25 }

在第19 行,您不必再声明添加派生:Employee(eid, name)

FullTimeEmployee(int eid, string name, int salary);

所以如果它是一个完整的程序,代码可能会喜欢这样

#include <iostream>
using namespace std;
class Employee{
public:
Employee(int eid, string name){}
};
class FullTimeEmployee:Employee{
private: 
int salary;
int eid = 10;
string name = "hei";
public: 
FullTimeEmployee(int eid, string name, int salary);
int getSalary(){ return salary; }    
};

FullTimeEmployee::FullTimeEmployee(int eid, string name, int salary):Employee(eid, name){
this->salary = salary;
};

int main()
{
FullTimeEmployee f(10, "yuza", 200);
cout<<f.getSalary();
return 0;
}

你可以构造一个派生类的构造函数

,如下所示:
#include <iostream>
class base { // the base class
int x, y;
public:
base() {} // default constructor
base(int a, int b) : x(a), y(b) {};
};
class derived : public base {
int m, n;
public:
derived(int, int); // derived class's constructor with its signature
void print(void) {
std::cout << m << ' ' << n << std::endl;
}
};
derived :: derived(int Dx, int Dy) { // coding the constructor of derived class
// outside of the class.
m = Dx;
n = Dy;
}
int main(void) {
derived d(5, 3); // instantiating the object of the derived class
d.print(); // will print 5 <space> 3
return 0;
}