如果基础抽象类没有构造函数firstname , lastname
,当您创建派生类的对象时,您将如何为任何派生类的成员赋值?
假设有一个Manager Class
派生的,Employee
从中添加Salary
数据和实现earning()
。NowEmployee
是一个抽象类,但Manager
它是一个concrete class
,因此您可以拥有一个Manager
. 但是当你实例化时Manager
,你需要初始化/赋值给继承自的成员base class i.e. Employee
。一种方法是您可以setFirstName() & setLastName()
为此目的在基类中使用它们,并且可以在构造函数中使用它们,derived class i.e. Manager
或者更方便的方法是在您的base abstract class Employee
.
请看下面的代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Employee {
public:
Employee(const char*, const char*);
~Employee();
const char* getFirstName() const;
const char* getLastName() const;
virtual double earnings() const=0; // pure virtual => abstract class
virtual void print() const;
private:
char* firstname;
char* lastname;
};
Employee::Employee(const char* first, const char* last){
firstname= (char*) malloc((strlen(first)+1)*sizeof(char));
lastname= (char*) malloc((strlen(last)+1)*sizeof(char));
strcpy(firstname,first);
strcpy(lastname,last);
}
Employee::~Employee(){
free(firstname);
free(lastname);
cout << "Employee destructed" << endl;
}
const char* Employee::getFirstName() const{ return firstname;}
const char* Employee::getLastName() const{ return lastname; }
void Employee::print() const{
cout << "Name: " << getFirstName() << " " << getLastName() << endl;
}
class Manager:public Employee{
public:
Manager(char* firstname,char* lastname,double salary):
Employee(firstname,lastname),salary(salary){}
~Manager(){}
double earnings() const {return salary;}
private:
double salary;
};
int main(){
Manager Object("Andrew","Thomas",23000);
Object.print();
cout << " has Salary : " << Object.earnings() << endl;
return 0;
}