所谓参数初始化列表,大概格式为 Test(char *_name, int _id) : name(_name) ,id(_id)
这里就从几种需要使用参数初始化列表的情况来说吧。
第一种,当成员变量被const关键字修饰的时候。
#include <iostream>
#include "string.h"
using namespace std;
class Test
{
private:
const int id;
char *name;
public:
Test(int _id, char *_name);
void show();
};
Test::Test(int _id, char *_name) : id(_id)
{
name = new char [128];
strcpy (name,_name);
}
void Test::show()
{
cout << id << " " << name << endl;
}
int main()
{
Test t(10, "HIK");
t.show();
return 0;
}
在这里的Test构造函数中,就用到了初始化成员列表,这段代码虽然有些欠缺,但还是可以运行的,类中的成员变量id被const所修饰,倘若把初始化函数变作如下形式
Test::Test(int _id, char *_name) //: id(_id)
{
name = new char [128];
strcpy (name,_name);
id = _id;
}
则编译的时候就会报错。可见被const修饰的成员变量只能用参数初始化列表对其赋值。
第二种情况,我们来举个例子吧,现在有个点类Point,里面包含了x,y轴坐标值两个成员变量,另一个类Circle 圆,需要一个点类对象作为其成员参数,当然他还有一个半径r是成员变量,综上我们可以写出如下代码
#include <iostream>
#include "string.h"
using namespace std;
class Point
{
public:
int x;
int y;
public:
Point(int _x, int _y)
{
x = _x;
y = _y;
}
};
class Circle
{
public:
Point center;
int r;
public:
Circle(int _x, int _y, int _r) : center(_x, _y)
{
r = _r;
}
};
int main()
{
Circle (6, 6, 6);
return 0;
}
这个只是一个测试代码,编译运行没有出现错误,也没有什么现象,这里值得指出的是,可能有部分同仁也会犯我编写代码时候犯得一个错误,即在初始化列表中画蛇添足,加上一个Point的构造函数,写成Circle(int _x, int _y, int _r) : center.Point(_x, _y)
,这是错误的。式中center作为类Circle的成员变量,可以理解为圆在坐标轴里面的圆心坐标。在这儿相当于调用其析构函数对其赋值。鉴于c++是面向对象开发的语言,再次也不再做过多讲解,就算是记住这类题型。
第三种情况便是在继承中。假设类Parent 派生出类Child,那么类Parent中成员变量的初始化,需要在类Child中使用初始化列表来完成,且看如下代码:
#include <iostream>
#include "string.h"
using namespace std;
class Parent
{
public:
int p;
public:
Parent(int _p)
{
p = _p;
}
};
class Child : public Parent
{
public:
int c;
public:
Child(int _p, int _c) : Parent(_p)
{
c = _c;
}
};
int main()
{
Child ch(1, 2);
return 0;
}
在类Child中,其构造函数便采用了初始化列表对其父类Parent进行了赋值操作。
所以到目前所学的章节知识中,三种需要用到参数初始化列表的情况小结如下:
1、cosnt修饰的成员变量
2、一个类中,包含另一个类定义的对象作为成员变量
3、子类对父类变量的初始化