构造函数初始化列表是显式的初始化类的成员;而没使用初始化列表的构造函数是对类的成员赋值,初始化和赋值对内置类型的成员没有什么大的区别,对非内置类型成员变量,为了避免两次构造,推荐使用类构造函数初始化列表。但有的时候必须用带有初始化列表的构造函数:
1.成员类型是没有默认构造函数的类。若没有提供显示初始化式,则编译器隐式使用成员类型的默认构造函数,若类没有默认构造函数,则编译器尝试使用默认构造函数将会失败
2.const成员或引用类型的成员。因为const对象或引用类型只能初始化,不能在构造函数中对他们赋值
列子如下:const成员或引用类型的成员使用初始化列表
#include<iostream>
using namespace std;
class son{
public:
//构造函数是给成员隐式赋值初始化,初始化列表是显示初始化类的成员
//son(int aa,int bb) :a(aa),b(c)
/*son() :b(c)
{
c = 100;
cout << "默认构造函数" << endl;
}
/*son()
{
c = 100;
//b = c;编译器会报错,引用成员为提供初始设定值
cout << "默认构造函数" << endl;
}*/
void print()
{
cout << c << endl;
cout << a << endl;
cout << b << endl;
}
public:
const int a=100;
int c;
int& b;
};
int main()
{
//son s(100,100);
son s;
s.print();
system("pause");
}
2成员类型是没有默认构造函数的类使用初始化列表
#include<iostream>
using namespace std;
class A
{
public:
A(int age)
{
this->age = age;
cout << "A有参构造" << endl;
}
A(A& a)
{
cout << "A拷贝构造" << endl;
}
~A()
{
cout << "析构A" << endl;
}
public:
int age;
};
class B
{
public:
//方式1
/*B() :a(10), age(20)
{
cout << "A::age=" << a.age << " B::age=" << age << endl;
cout << "B默认构造中的初始化列表" << endl;
}*/
//方式2
B(int t1,int t2) :a(t1), age(t2)
{
cout << "A::age=" << a.age << " B::age=" << age << endl;
cout << "B有参构造中的初始化列表构造" << endl;
}
~B()
{
cout << "析构B" << endl;
}
public:
A a;
int age;
};
void test()
{
//B b;
B b(30, 40);
getchar();
}
int main()
{
test();
system("pause");
}
结果: