派生类构造函数规则
如果基类拥有构造函数但是没有默认构造函数,那么派生类的构造函数必须显示的调用基类的某个构造函数。
以B类从A类派生为例,我们总结如下:
1、若B有构造函数而A没有,当创建B类的对象时,B的相应构造函数被自动调用。
2、若B没有构造函数而A有,则A必须拥有默认构造函数,只有这样,当创建B类的对象时,才能自动执行A的默认构造函数。
3、若B有构造函数,且A有默认构造函数,则创建B类的对象时,A的默认构造函数会自动执行,除非当前被调用的派生类构造函数在其初始化段中显示的调用了A的非默认构造函数。
4、若B和A都有构造函数,但A没有默认构造函数,则B的每个构造函数必须在其初始化段中显示地调用A的某个构造函数。只有这样,当创建B的对象时,A的构造函数才能获得执行机会。
再次强调,在创建派生类对象时,必须显示地或隐式地执行其基类的某个构造函数,这一点非常重要,有时候,派生类的构造函数可能会依赖基类的构造函数来完成一些必要的操作,例如,依赖基类的构造函数来完成部分数据成员的初始化。而且,一般可以认为派生类对象是对基类对象的特化,这进一步说明了为什么基类的构造函数(如果该类有构造函数)必须在派生类对象创建时首先执行,在此之后,派生类的构造函数再负责处理派生类中的特化信息(派生类中的新增数据成员)。
代码实例:(1)
<span style="font-size:14px;">#include <iostream>
using namespace std;
class A
{
public:
private:
int x;
};
class B:public A
{
public:
B(int c)
{
y=c;
cout<<"Bb"<<endl;
}
void fun()
{
cout<<"in B fun"<<endl;
}
private:
int y;
};
int main(void)
{
A *b=new B(2);
system("pause");
return 0;
}</span>
执行结果为Bb
代码实例(2)
#include <iostream>
using namespace std;
class A
{
public:
A() {cout<<"Aa"<<endl; }
private:
int x;
};
class B:public A
{
public:
private:
int y;
};
int main(void)
{
A*b=new B;
system("pause");
return 0;
}
执行结果为Aa
代码实例(3):
<span style="font-size:14px;">#include <iostream>
using namespace std;
class A
{
public:
A() {cout<<"Aa"<<endl; }
A(int c)
{
x=c;
cout<<"A"<<endl;
}
void fun()
{
cout<<"in A fun"<<endl;
}
private:
int x;
};
class B:public A
{
public:
/*
B(int c,int b) :A(c)
{
y=b;
cout<<"B"<<endl;
}
*/
B(int c)
{
y=c;
cout<<"Bb"<<endl;
}
void fun()
{
cout<<"in B fun"<<endl;
}
private:
int y;
};
int main(void)
{
//A *a=new B(2,3);
A *b=new B(2);
// A*b=new B;
system("pause");
return 0;
}</span>
执行结果是Aa Bb
代码实例(4)
<span style="font-size:14px;">#include <iostream>
using namespace std;
class A
{
public:
//A() {cout<<"Aa"<<endl; }
A(int c)
{
x=c;
cout<<"A"<<endl;
}
private:
int x;
};
class B:public A
{
public:
B(int c,int b) :A(c)
{
y=b;
cout<<"B"<<endl;
}
/*
B(int c)
{
y=c;
cout<<"Bb"<<endl;
} */
private:
int y;
};
int main(void)
{
A *a=new B(2,3);
//A *b=new B(2);
// A*b=new B;
system("pause");
return 0;
}</span>
执行结果A B
代码实例(5)
<span style="font-size:14px;">#include <iostream>
using namespace std;
class A
{
public:
A() {cout<<"Aa"<<endl; }
A(int c)
{
x=c;
cout<<"A"<<endl;
}
private:
int x;
};
class B:public A
{
public:
B(int c,int b) :A(c)
{
y=b;
cout<<"B"<<endl;
}
B(int c)
{
y=c;
cout<<"Bb"<<endl;
}
private:
int y;
};
int main(void)
{
A *a=new B(2,3);
A *b=new B(2);
system("pause");
return 0;
} </span>
执行结果A B Aa Bb