阅读程序(1)
#include <iostream>
using namespace std;
class Data
{
public:
Data(int i):x(i){cout<<"A";}
~Data(){ cout<<"B";}
private:
int x;
};
class Base
{
public:
Base(int i):b1(i){cout<<"C";}
~Base(){ cout<<"D";}
private:
int b1;
};
class Derived:public Base
{
public:
Derived (int i,int j):Base(i),d1(j){
cout<<"E";
}
~Derived(){cout<<"F";}
private:
Data d1;
};
int main()
{
Derived obj(1,2);
return 0;
}
学习心得:在类的释放过程中,先释放类,在释放此类中定义的其他类
阅读程序(2)
#include <iostream>
using namespace std;
class A
{
public:
A(){a=0;}
A (int i){a=i;}
void print(){cout<<a<<" ";}
private:
int a;
};
class B: public A
{
public:
B(){b=0;}
B(int i, int j, int k): A(i),aa(j){b=k;}
//思考:这3处出现的print,有何区别
void print() //(1)
{
A::print(); //(2)
aa.print(); //(3)
cout<<b<<endl;
}
private:
int b;
A aa;
};
int main()
{
B test[2];
test[0]=B(1,4,7);
test[1]=B(2,5,8);
for(int i=0; i<2; i++)
test[i].print();
return 0;
}
学习心得:A(i)是对基类中a进行初始化,而aa(i)则是私有成员aa的初始化,两个存在区别。
阅读程序(4)
#include <iostream>
using namespace std;
class Base
{
public:
Base(char i) { cout<<"Base constructor. --"<<i<<endl; }
};
class Derived1:virtual public Base
{
public:
Derived1(char i,char j):Base(i){
cout<<"Derived1 constructor. --"<<j<<endl;
}
};
class Derived2:virtual public Base
{
public:
Derived2(char i,char j):Base(i){
cout<<"Derived2 constructor. --"<<j<<endl;
}
};
class MyDerived: public Derived1,public Derived2
{
public:
MyDerived(char i,char j,char k,char l,char m,char n,char x):
Derived2(i,j), Derived1(k,l), Base(m), d(n){
cout<<"MyDerived constructor. --"<<x<<endl;
}
private:
Base d;
};
int main()
{
MyDerived obj('A','B','C','D','E','F','G');
return 0;
}
运行结果:
学习心得:刚看到这个结果的时候很吃惊,跟自己想象的完全不一样,我又仔细看了一下,看到virtual才想起老师讲的虚基类,看到结果,这里边的机制应该是先初始化最基类,再按定义顺序分别进行初始化。