初始化列表和函数体内初始化是有差异的。
成员初始化列表是在数据成员定义的同时赋初值,但是构造函的函数体是采用先定义后赋值的方式来做
当我们在用类a作为另一个类b的成员时,若类a中有有参构造函数,对其进行初始化可以这样写
#include <iostream>
using namespace std;
class Point
{
public:
Point(double xx, double yy)
{
Point::x = xx;
Point::y = yy;
};
void Display()
{
cout << x << " " << y << endl;
}
double x;
double y;
};
class Circle
{
private:
Point p; //圆心点
double r; //圆半径
public:
Circle(double x1, double y1, double r1) :p(x1, y1), r(r1) {};
void Display()
{
p.Display();
cout << r;
}
};
int main()
{
double a, b, c;
cin >> a >> b >> c;
Circle a1(a, b, c);
a1.Display();
return 0;
}
因为初始化列表是定义的同时赋初值,所以这里我们可以创建一个Point类的变量
但如果我们在函数体内初始化的话他是先定义再赋值,而我们用p.x = x1;的话,他会默认创建一个无参构造函数,但我们Point中没有无参构造函数所以会报错