建構子初始化列表
語法
建構子初始化列表(Initialization list of constructors)
語法如下
類別名(資料型態 參數名1, 資料型態 參數名2, ...):成員變數1(參數名1),成員變數2(參數名2), ... {}
程式碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Student {
public:
string m_name;
int m_age;
public:
Student() {
cout << "沒參數建構子" << endl;
}
Student(string name, int age):m_name(name),m_age(age) {
cout << "初始化列表建構子" << endl;
}
~Student() {
cout << "解構子" << endl;
}
void print() {
cout << "name: " << m_name << endl;
cout << "age: " << m_age << endl;
}
};
int main() {
Student s1("cici", 18);
s1.print();
return 0;
}
初始化列表建構子
name: cici
age: 18
解構子
建構子初始化
使用以下方式初始化。
建構子() : 成員變數名(初始值), 成員變數名(初始值) {}
Student() : name_(nullptr), id_(0) {}
程式碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;
class MyClass {
public:
const char* name_;
int id_;
MyClass() : name_(nullptr), id_(0) {
cout << "無參數建構子" << endl;
}
};
int main() {
MyClass myclass;
return 0;
}
無參數建構子
初始化列表與運算式
下方有參數的建構子,使用初始化列表並加上運算式,初使化成員變數。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Student {
public:
string m_name;
int m_age;
public:
Student() {
cout << "沒參數建構子" << endl;
}
Student(string name, int age):m_name("漂亮的" + name),m_age(age + 10) {
cout << "初始化列表建構子" << endl;
}
~Student() {
cout << "解構子" << endl;
}
void print() {
cout << "name: " << m_name << endl;
cout << "age: " << m_age << endl;
}
};
int main() {
Student s1("cici", 18);
s1.print();
return 0;
}
初始化列表建構子
name: 漂亮的cici
age: 28
解構子