1 #include <iostream> 2 #include<stdlib.h> 3 using namespace std; 4 5 class A 6 { 7 public: 8 int _a; 9 A() 10 { 11 _a = 1; 12 } 13 void print() 14 { 15 printf("%d ", _a); 16 } 17 }; 18 19 class B: public A 20 { 21 public: 22 int _a; 23 B() 24 { 25 _a = 2; 26 } 27 }; 28 29 int main() 30 { 31 B b; 32 b.print(); 33 printf("%d ", b._a); 34 return 0; 35 }
运行的结果为:
子类会覆盖父类的变量
1 #include <iostream> 2 #include<stdlib.h> 3 using namespace std; 4 5 class base 6 { 7 private: 8 int m_i; 9 int m_j; 10 public: 11 base(int i):m_j(i),m_i(m_j){} 12 base():m_j(0),m_i(m_j){} 13 int get_i(){return m_i;} 14 int get_j(){return m_j;} 15 }; 16 17 int main() 18 { 19 base obj(98); 20 cout<<obj.get_i()<<endl 21 <<obj.get_j()<<endl; 22 23 return 0; 24 }
运行结果为:
构造函数的初始化变量顺序是按照成员变量的声明顺序来执行的。