C++第01課 C++與C的區別(七)
阿新 • • 發佈:2021-09-03
1.結構體基本區別
struct MM { char name[20]; int age; void print() //預設為行內函數 { cout << name << "\t" << age << endl; } }; int main() { //1.定義變數時省略關鍵字 struct MM m;//C語言方式 MM mm; //2.new MM MM* pMM = new MM; MM* pMMArr = new MM[4]; //3.結構體可以包含函式MM mm1 = { "mm1",18 }; MM mm2 = { "mm2",17 }; MM* pmm = &mm2; mm1.print(); pmm->print(); return 0; }
2.結構體的構造
struct Empty { void print() { cout << "空的結構體" << endl; } }; //C++允許在定義結構體時給資料賦值,當我們構建一個沒有初始化的物件時採取預設值 struct MM { char name[20] = "小可愛"; int age = 16; MM() = default; MM(const char* name,int age):age(age){ strcpy(this->name, name); } void print() { cout << name << "\t" << age << endl; } }; struct Boy { int age; //刪掉預設建構函式 Boy() = delete; }; int main() { cout<< sizeof(struct Empty) << endl; //空的結構體佔用一個位元組的標識位(函式對結構體記憶體不影響) MM mm; mm.print(); MM mm1 = { "小甜心",18 }; mm1.print(); //建立物件的過程就是呼叫建構函式的過程 MM mm2("小寶貝", 19); mm2.print(); //new物件的過程也是呼叫建構函式的過程 //先建立一個無名物件,然後把無名物件的首地址賦值給指標 MM* mm3 = new MM("張三",14); mm3->print(); return 0; }
3.結構體的幾種初始化方式
struct Boy { //1.定義結構體的時候初始化 char name[20]="張三"; int age=10; //2.建構函式完成資料初始化 常用 Boy() = default; Boy(const char* name, int age) :age(age) { strcpy(this->name, name); } //3.通過成員函式傳參 void init(const char* name, int age) { strcpy(this->name, name); this->age = age; } //4.提供返回引用 int& getAge() { return age; } void print() { cout << name << "\t" << age << endl; } };
4.建構函式對定義變數的影響
struct Test { char name[20]; int age; Test(const char* name, int age) { strcpy(this->name, name); this->age = age; cout << "呼叫建構函式" << endl; } void print() { cout << name << "\t" << age << endl; } }; void print(Test t) {//傳參是賦值方式 t.print(); } int main() { //下面的程式碼也是呼叫建構函式的過程 Test t = { "張三",12 }; //呼叫兩個引數的建構函式 Test t1("李四", 15); t1 = t; //和Test t = { "張三",12 }; 完全不一樣 t1.print(); return 0; }