三種結構體初始化方法
1 默認無參的構造函數
2 結構體自帶的默認構造函數
3 帶參數的自定義的構造函數
struct node{ int data; string str; char x; node() :x(), str(), data(){} //無參數的構造函數數組初始化時調用 node(int a, string b, char c) :data(a), str(b), x(c){}//有參構造 void init(int a, string b, char c){//自定義的構造函數 this->data = a; this->str = b; this->x = c; } }N[10];
**要點**:
在建立結構體數組時, 如果只寫了帶參數的構造函數將會出現數組無法初始化的錯誤!!!各位同學要牢記呀!
下面是一個比較安全的帶構造的結構體示例
下面我們分別使用默認構造和有參構造,以及自己手動寫的初始化函數進行會結構體賦值
並觀察結果
測試代碼如下:
#include <iostream> #include <string> using namespace std; struct node{ int data; string str; char x; //自己寫的初始化函數 void init(int a, string b, char c){ this->data = a; this->str = b; this->x = c; } node() :x(), str(), data(){} node(int a, string b, char c) :x(c), str(b), data(a){} }N\[10\]; int main() { N\[0\] = { 1,"hello",'c' }; N\[1\] = { 2,"c++",'d' }; //無參默認結構體構造體函數 N\[2\].init(3, "java", 'e'); //自定義初始化函數的調用 N\[3\] = node(4, "python", 'f'); //有參數結構體構造函數 N\[4\] = { 5,"python3",'p' }; //現在我們開始打印觀察是否已經存入 for (int i = 0; i < 5; i++){ cout << N\[i\].data << " " << N\[i\].str << " " << N\[i\].x << endl; } system("pause"); return 0; }
**輸出結果**
1 hello c 2 c++ d 3 java e 4 python f 5 python3 p
發現與預設的一樣結果證明三種賦值方法都起了作用, 好了就寫到這里.