1、构造函数的初始化列表
例1
class CDate
{
public:
CDate(int y, int m, int d)
{
_year = y;
_month = m;
_day = d;
}
void show()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
class CGoods
{
public:
CGoods(const char *n, int a, double p, int y, int m, int d)
:_date(y, m, d)
,_amount(a)
,_price(p)
{
strcpy(_name, n);
}
void show()
{
cout << "name:" << _name << endl;
cout << "amount:" << _amount << endl;
cout << "price:" << _price << endl;
_date.show();
}
private:
char _name[20];
int _amount;
double _price;
CDate _date;
};
int main()
{
CGoods good("商品", 100, 35.0, 2021, 9, 8);
good.show();
return 0;
}
例2—成员变量的初始化和它们定义的顺序有关,和构造函数初始化列表中出现的先后顺序无关!
我们看下面代码,打印的值是多少? 成员变量的初始化和它们定义的顺序有关,和构造函数初始化列表中出现的先后顺序无关!
class Test
{
public:
Test(int data = 10) :mb(data), ma(mb) {}
void show() { cout << "ma:" << ma << " mb:" << mb << endl; }
private:
int ma;
int mb;
};
int main()
{
Test t;
t.show();
return 0;
}
|