一、定義與使用
struct構造函數是在C++中定義和使用結構體時的一個重要概念,主要用於給結構體的成員變量進行初始化。
struct Person{
string name;
int age;
Person(string n, int a):name(n),age(a){}
};
Person p("Jack", 25);
如上例所示,我們在定義Person結構體時,傳入了兩個參數n和a,並將其賦值給了name和age成員變量。然後,我們在實例化Person對象時,直接將參數傳入構造函數,使得對象初始化時就擁有了name和age屬性。
二、構造函數的重載
在C++中,我們可以定義多個構造函數,以用於不同的初始化過程或情況。這種方法叫做構造函數的重載。
struct Student{
string name;
int age;
int id;
Student(string n, int a, int i):name(n),age(a),id(i){}
Student(string n):name(n){}
};
Student s1("Tom", 18, 2021010001);
Student s2("Jerry");
如上例所示,我們使用了兩個不同的構造函數來初始化Student對象。在第一個構造函數中,我們傳入了三個參數n、a和i,並將其賦值給了name、age和id成員變量;在第二個構造函數中,我們僅傳入了一個參數n,並將其賦值給了name成員變量。這樣,使得實例化對象的過程更加靈活方便。
三、默認構造函數
默認構造函數是指沒有參數或者所有參數都有默認值的構造函數。如果我們沒有定義任何構造函數,C++編譯器會自動生成一個默認構造函數,以用於對象的實例化。
struct Book{
string name;
int price;
Book(){}
};
Book b;
如上例所示,我們定義了一個Book結構體,並沒有傳遞任何參數給默認構造函數,然後通過實例化對象b來使用它。此時,對象的成員變量都被初始化為默認值。
四、拷貝構造函數
拷貝構造函數是用於創建新對象時,將已有對象的值傳遞給新對象的構造函數。它是採用一個常量引用參數的構造函數來實現的。
struct Car{
string brand;
int price;
Car(){}
Car(const Car &c){
brand = c.brand;
price = c.price;
}
};
Car c1;
c1.brand = "BMW";
c1.price = 500000;
Car c2(c1);
如上例所示,我們定義了一個Car結構體,並且重載了拷貝構造函數。在實例化c2時,我們將c1作為參數傳遞給它的拷貝構造函數,從而實現了將c1對象的值拷貝到c2中。
五、析構函數
析構函數是在對象被銷毀時自動調用的函數,它負責清理對象被分配的內存空間和資源。
struct Dog{
string name;
Dog(){}
~Dog(){
cout << "Dog is destroyed." << endl;
}
};
Dog *d = new Dog();
delete d;
如上例所示,我們定義了一個Dog結構體,並在其中重載了析構函數。在實例化d對象時,我們使用了new運算符來為它分配內存空間,在對象被銷毀時,C++編譯器會自動調用析構函數來清理內存空間。此時,我們在析構函數中打印了一條消息來驗證析構函數的調用情況。
六、總體代碼
#include
#include
using namespace std;
struct Person{
string name;
int age;
Person(string n, int a):name(n),age(a){}
};
struct Student{
string name;
int age;
int id;
Student(string n, int a, int i):name(n),age(a),id(i){}
Student(string n):name(n){}
};
struct Book{
string name;
int price;
Book(){}
};
struct Car{
string brand;
int price;
Car(){}
Car(const Car &c){
brand = c.brand;
price = c.price;
}
};
struct Dog{
string name;
Dog(){}
~Dog(){
cout << "Dog is destroyed." << endl;
}
};
int main(){
Person p("Jack", 25);
Student s1("Tom", 18, 2021010001);
Student s2("Jerry");
Book b;
Car c1;
c1.brand = "BMW";
c1.price = 500000;
Car c2(c1);
Dog *d = new Dog();
delete d;
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/296076.html
微信掃一掃
支付寶掃一掃