C++工程实战入门笔记11-三种初始化成员变量的方式
·
1. 默认成员初始化器 (C++11)
在类声明中直接给成员变量赋初值。
class MyClass {
public:
MyClass() {} // 构造函数可以使用这些默认值
private:
int x = 0; // 默认成员初始化
string name = "default";
vector<int> data{1, 2, 3}; // 使用大括号初始化
};
2. 构造函数的成员初始化器列表
在构造函数参数列表后使用冒号初始化成员。
class MyClass {
public:
// 成员初始化器列表
MyClass(int value, const string& n) : x(value), name(n), data{1, 2, 3} {
// 构造函数体
}
private:
int x;
string name;
vector<int> data;
};
3. 构造函数中赋值
在构造函数体内使用赋值语句。
class MyClass {
public:
MyClass(int value, const string& n) {
// 构造函数体内赋值
x = value;
name = n;
data = {1, 2, 3}; // 需要先默认构造,再赋值
}
private:
int x;
string name;
vector<int> data;
};
# 例子
class Student {
public:
// 推荐:使用成员初始化器列表 + 默认成员初始化器
Student(int id, const string& n)
: studentId(id), name(n) // 必须用初始化列表的
{
// 构造函数体
}
// 重载构造函数
Student() : studentId(0) {
// 使用默认成员初始化器的值
}
private:
const int studentId; // const成员必须用初始化列表
string name = "Unknown"; // 默认值
vector<string> courses{}; // 空列表初始化
int score = 60; // 基本类型默认值
};
// 使用
Student s1(123, "Alice"); // studentId=123, name="Alice", score=60
Student s2; // studentId=0, name="Unknown", score=60
更多推荐



所有评论(0)