C++:初始化成员变量(无参构造|有参构造|初始化列表)


通常我们需要对成员变量进行初始化操作,主要有以下几种方法

1 无参构造函数初始化成员变量

在无参构造函数中初始化成员变量

示例代码:

#include <iostream>
#include <string>

using namespace std;

class Person
{
    
    
public//在无参构造函数中初始化成员变量
	Person()
	{
    
    
		m_age = 18;
		m_weight = 72.5;
		m_sex = "男";
	}
	
public:
	int m_age;
	double m_weight;
	string m_sex;

};

int main()
{
    
    
	Person Zhang;
	cout << "姓名:" << Zhang.m_age << endl;
	cout << "体重:" << Zhang.m_weight << endl;
	cout << "性别:" << Zhang.m_sex << endl;
}

输出结果:

姓名:18
体重:72.5
性别:男

2 在有参构造函数的形参列表中初始化成员变量

示例代码:

#include <iostream>
#include <string>

using namespace std;

class Person
{
    
    
public:
	//在有参构造函数中初始化成员变量
	Person(int age, double weight, string sex)
	{
    
    
		m_age = age;
		m_weight = weight;
		m_sex = sex;
	}

public:
	int m_age;
	double m_weight;
	string m_sex;

};

int main()
{
    
    
	Person Zhang(18, 72.5, "男");
	cout << "姓名:" << Zhang.m_age << endl;
	cout << "体重:" << Zhang.m_weight << endl;
	cout << "性别:" << Zhang.m_sex << endl;
}

输出结果:

姓名:18
体重:72.5
性别:男

3 使用初始化列表初始化成员变量

语法:
构造函数(): 成员变量1(), 成员变量2(), 成员变量3(), 成员变量n() {}

3.1 无参构造函数使用初始化列表

示例代码:

#include <iostream>
#include <string>

using namespace std;

class Person
{
    
    
public:
	//无参构造函数使用初始化列表
	Person() :m_age(18), m_weight(72.5), m_sex("男")
	{
    
    

	}

public:
	int m_age;
	double m_weight;
	string m_sex;

};

int main()
{
    
    
	Person Zhang;
	cout << "姓名:" << Zhang.m_age << endl;
	cout << "体重:" << Zhang.m_weight << endl;
	cout << "性别:" << Zhang.m_sex << endl;
}

输出结果:

姓名:18
体重:72.5
性别:男

3.2 有参构造函数使用初始化列表

示例代码:

#include <iostream>
#include <string>

using namespace std;

class Person
{
    
    
public:
	//有参构造函数使用初始化列表
	Person(int age, double weight, string sex) :m_age(age), m_weight(weight), m_sex(sex)
	{
    
    
		
	}

public:
	int m_age;
	double m_weight;
	string m_sex;

};

int main()
{
    
    
	Person Zhang(18, 72.5, "男");
	cout << "姓名:" << Zhang.m_age << endl;
	cout << "体重:" << Zhang.m_weight << endl;
	cout << "性别:" << Zhang.m_sex << endl;
}

输出结果:

姓名:18
体重:72.5
性别:男

4 在声明成员变量时初始化

示例代码:

#include <iostream>
#include <string>

using namespace std;

class Person
{
    
    
public:
	int m_age = 18;
	double m_weight = 72.5;
	string m_sex = "男";

};

int main()
{
    
    
	Person Zhang;

	cout << "姓名:" << Zhang.m_age << endl;
	cout << "体重:" << Zhang.m_weight << endl;
	cout << "性别:" << Zhang.m_sex << endl;
}

输出结果:

姓名:18
体重:72.5
性别:男

猜你喜欢

转载自blog.csdn.net/weixin_46098577/article/details/122223452