#include "StdAfx.h"
#include<iostream>
using namespace std;



class rootClass {
public: int rpub_data;
//rootClass():rpub_data(0),rpri_data(0),rpro_data(0){}
rootClass(int aa=2,int bb=2,int cc=2){
rpub_data=aa;
rpri_data=bb;
rpro_data=cc;
}
void show_r_data(){
cout<<"public data: "<<rpub_data<<endl;
cout<<"private data: "<<rpri_data<<endl;
cout<<"protected data: "<<rpro_data<<endl;
}
void set_r_data(int aa,int bb,int cc){
rpub_data=aa;
rpri_data=bb;
rpro_data=cc;
}
private:
int rpri_data;
protected:
int rpro_data;
};

//define the children class

class childrenClass:public rootClass{
public:
childrenClass(){}
childrenClass(int para1,int para2,int para3){
rootClass( para1, para2, para3);
}
void show_children_data(){
show_r_data();
}
void set_children_data(int aa,int bb,int cc){
set_r_data(aa,bb,cc);
}
};


void main()
{
childrenClass init;
cout<<"init's public data: "<<init.rpub_data<<endl;
cout<<"use rootclass's method to show all the data: ";
init.show_r_data();
cout<<"use init's own method to show all the data: ";
init.show_children_data();
  childrenClass afterinit(1,2,3);
//afterinit.set_children_data(1,2,3);
afterinit.show_children_data();
}

为什么afterinit的输出还是2,2,2,而不是1,2,3?

推荐图书

  • C++ Primer中文版(第4版)
  • More Effective C++:35个改善编程与设计的有效方法(中文版)
  • 设计模式:可复用面向对象软件的基础


1个回答

childrenClass(int para1,int para2,int para3){
rootClass( para1, para2, para3);
}

你这里构造的是一个临时对象,而不是初始化基类部分。google"初始化列表"