【发布时间】:2020-05-18 11:55:29
【问题描述】:
我想我在下面的代码中做错了。我想继承Employee类中Person类的方法。
#include<bits/stdc++.h>
using namespace std;
class Person{
private:
string name;
int age;
public:
Person(string name, int age){ //Base parameterized constructor
name = name;
age = age;
}
void getName(){
cout<<"Name: "<<name<<endl;
}
void getAge(){
cout<<"Age: "<<age<<endl;
}
};
class Employee: public Person{ //Default inheritance type is private
private:
int employeeID;
public:
Employee(string name, int age, int id) : Person(name, age){ //Derived parameterized constructor
employeeID = id;
}
void getEmployeeDetails(){
getName();
getAge();
cout<<"Employee ID: "<<employeeID<<endl;
}
};
int main(){
Employee* e = new Employee("John", 24, 14298);
e->getEmployeeDetails();
return 0;
}
我得到以下输出:
姓名:
年龄:0
员工编号:14298
请让我知道我在这里缺少什么。任何帮助将不胜感激!
【问题讨论】:
-
您正在使用 new 在堆上创建您的 Employee e,但永远不要删除它。在这种情况下这无关紧要,因为您的程序会立即终止,但从技术上讲,这是内存泄漏。一旦不再需要它,您需要调用删除您的 Employee*,使用智能指针或使用 Employee e("John", 24, 14298); 在堆栈上创建 e。这与您的问题无关,但如果您不知道,我认为值得一提。
标签: c++ oop inheritance