初始化列表定义:
与其他函数不同,构造函数除了有名字,参数列表和函数体之外,还可以有初始化列表,初始化列表以冒号开头,后跟一系列以逗号分隔的初始化字段。
class foo
{
public:
foo(string s, int i) :name(s), id(i) {}; // 初始化列表
private:
string name; int id;
};
示例:
class Test1
{
public:
Test1() // 无参构造函数
{
cout << "Construct Test1" << endl;
}
Test1(const Test1& t1) // 拷贝构造函数
{
cout << "Copy constructor for Test1" << endl; this->a = t1.a;
}
Test1& operator = (const Test1& t1) // 赋值运算符
{
cout << "assignment for Test1" << endl; this->a = t1.a; return *this;
}
int a;
};
class Test2
{
public:
Test1 test1;
Test2(Test1 &t1)
{
test1 = t1;
}
};
从概念