C++类中,派生类构造函数后面有初始化列表时,怎样将这个派生类构造函数分为声明和主体部分?
1个回答
展开全部
举个例子你就知道了
#include <iostream>
#include <string>
using namespace std;
class person
{
public:
person(){}
person(string m_name,string m_ID): name(m_name),ID(m_ID) {}
~person(){}
protected:
string name;
string ID;
};
class manager : public person
{
public:
manager(){}
manager(string m_name,string m_ID,string m_department); //声明构造函数
~manager(){}
void display()
{
cout<<name<<" "<<ID<<" "<<department<<endl;
}
private:
string department;
};
//构造函数实现,用初始化列表的形式 ,调用基类的构造函数来初始化继承的信息
manager::manager(string m_name,string m_ID,string m_department):person(m_name,m_ID),department(m_department)
{
}
int main()
{
manager * m = new manager("张三","201012016","技术部");
m->display();
delete m;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class person
{
public:
person(){}
person(string m_name,string m_ID): name(m_name),ID(m_ID) {}
~person(){}
protected:
string name;
string ID;
};
class manager : public person
{
public:
manager(){}
manager(string m_name,string m_ID,string m_department); //声明构造函数
~manager(){}
void display()
{
cout<<name<<" "<<ID<<" "<<department<<endl;
}
private:
string department;
};
//构造函数实现,用初始化列表的形式 ,调用基类的构造函数来初始化继承的信息
manager::manager(string m_name,string m_ID,string m_department):person(m_name,m_ID),department(m_department)
{
}
int main()
{
manager * m = new manager("张三","201012016","技术部");
m->display();
delete m;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询