默认构造函数的构造操作
1 成员对象带默认构造函数
1.1 行为
外部对象包含成员对象时,没有显式调用成员对象构造函数时,编译器会自动添加调用;
1.2 示例代码
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class B
{
private:
A a;
int value;
string name;
public:
B() {
name = "aloha";
}
void show()
{
cout << "B value=" << value << ",name=" << name <<endl;
};
};
int main()
{
B b;
b.show();
}
1.3 输出
call A()
B value=-858993460,name=aloha
备注:
若注释代码中的A的默认构造函数,编译将不通过,
需要在在B的构造函数中通过初始化列表方式显式调用A的非默认构造函数
B():a(0) {
name = "aloha";
}
2 父类型带默认构造函数
2.1 行为
子类型的构造函数中,自动会调用父类型的构造函数。
2.2 示例代码1
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class AA:public A
{
int value;
string name;
public:
AA() {
value = 0;
name = "aloha";
}
void show()
{
cout << "AA value=" << value << ",name=" << name << endl;
};
};
int main()
{
AA aa;
aa.show();
}
2.3 输出1
call A()
AA value=0,name=aloha
2.4 示例代码2
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class AA:public A
{
int value;
string name;
public:
AA()
{
value = 0;
name = "aloha";
}
AA(int value)
{
this->value = value;
name = "aloha";
}
void show()
{
cout << "AA value=" << value << ",name=" << name << endl;
};
};
int main()
{
AA aa(5);
aa.show();
}
2.5 输出2
call A()
AA value=5,name=aloha
3 两者兼有的情况
3.1 行为
先调用父类的默认构造方法,再调用成员对象的默认构造方法
3.2 示例代码
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class B
{
public:
B() {
cout << "call B()" << endl; }
B(int value) {
cout << "call B(value)" << endl; }
};
class AAB:public A
{
int value;
string name;
B b;
public:
AAB()
{
value = 0;
name = "aloha";
}
AAB(int value)
{
cout << "AAB start" << endl;
this->value = value;
name = "aloha";
cout << "AAB end" << endl;
}
void show()
{
cout << "AAB value=" << value << ",name=" << name << endl;
};
};
int main()
{
AAB aab(5);
aab.show();
}
3.3 输出
call A()
call B()
AAB start
AAB end
AAB value=5,name=aloha
4 参考资料
《深入探索C++对象模型》,美 Stanley B.Lippman 著,侯捷 译,电子工业出版社,2012年;