c++ 初始化列表构造函数初始化父类变量
c++ 初始化列表构造函数初始化父类变量,可以在构造时主动调用父类的含参构造函数
#include<iostream>
using namespace std;
class Person
{
public:
string _name;
string getNickName();
Person(string name):_name(name){};
private:
void initNickName();
string _nickName;
};
string Person::getNickName()
{
initNickName();
return _nickName;
}
void Person::initNickName()
{
_nickName="hahaha"+_name;
}
class Student: public Person
{
public:
Student(string name, int id):Person(name), _id(id){};
// Student(string name, int id):_name(name), _id(id){}; // 这样写会报错
int getId();
private:
int _id;
};
int Student::getId()
{
return _id;
}
int main (int argc, char *argv[]) {
cout<<"hello"<<endl;
Student stu("xiaoming", 10);
cout<<stu.getNickName()<<endl;
cout<<stu.getId()<<endl;
return 0;
}