記事ディレクトリ
通常、主に次の方法でメンバー変数を初期化する必要があります
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
性别:男