木子屋 Dnawo's BLOG

C++在构造函数中初始化成员变量的两种方法

👤 dnawo 📅 2010-11-22 👁 6351 👍 0 💬 0 🔄 来源:本站原创
C++在构造函数中初始化成员变量有两种方法:

class AA
{
public:
	AA(){x=1;y=2;}
	void ToString(){cout<<"x:"<<x<<endl;cout<<"y:"<<y<<endl;}
private:
	int x;
	int y;
};

class AA
{
public:
	AA():x(1),y(2){}
	void ToString(){cout<<"x:"<<x<<endl;cout<<"y:"<<y<<endl;}
private:
	int x;
	int y;
};

上边两种方法执行都是正确的,那有什么区别呢?如果有要初始化成员常量,则只能用第二种方法:

class AA
{
public:
	AA():x(1),y(2){}
	void ToString(){cout<<"x:"<<x<<endl;cout<<"y:"<<y<<endl;}
private:
	const int x;
	const int y;
};

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 C++默认构造函数 下一篇 → WinPE下硬盘安装WindowsXP问题汇总