还是继承与派生。。。
先上代码~~~#include<iostream.h>
class A{
private:
int a;
public:
A(){ a=0;cout<<"A′s defanlt constructor called.\n"; }
A(int i){ a=i;cout<<"A′s constructor called.\n"; }
void print(){ cout<<a<<","; }
~A(){ cout<<"A′s destructor called.\n"; }
int Geta(){ return a; }
};
class B: public A{
public:
B(){ b=0;cout<<"B′s defanlt constructor called.\n"; }
B(int i,int j,int k):A(i),aa(j){ b=k; cout<<"B′s constructor called.\n"; }
void print();
~B(){ cout<<"B′s destructor called.\n"; }
private:
int b;
A aa; //子对象,或称为成员对象
};
void B::print(){
A::print();
cout<<b<<","<<aa.Geta()<<endl;
}
void main(){
B bb[2]={B(1,2,5),B(3,4,7)};
for(int i=0;i<2;i++) bb[i].print();
}
运行结果:
A's constructor called.
A's constructor called.
B's constructor called.
A's constructor called.
A's constructor called.
B's constructor called.
1,5,2
3,7,4
B's destructor called.
A's destructor called.
A's destructor called.
B's destructor called.
A's destructor called.
A's destructor called.
我想问下,为什么在子对象调用构造函数的时候,调用的是
A(int i){ a=i;cout<<"A′s constructor called.\n"; }
而不是
A(){ a=0;cout<<"A′s defanlt constructor called.\n"; }
子对象aa不是不带参数吗?
后面析构函数调用同问。。。。不懂啊,到底什么时候调用缺省构造函数和缺省析构函数?