C++中構造函數的理解

構造函數

一.定義

*以類名作爲函數名

*無返回值類型

二.作用

*初始化對象的數據成員

*類對象被創建時,編譯器爲對象分配內存空間並自動調用構造函數以完成成員的初始化

三.種類

*無參構造

*一般構造((重載構造)帶有不同類型的參數

*拷貝構造

 

然後就寫了一個小代碼理解一下

12 #include<iostream>
13                                                    
14 using namespace std;
15 
16 class Student 
17 {
18 public:      //共有成員
19     //構造函數的重載規則和普通函數的重載相同,重載的時候不關注返回值,只關注參數類型
20     Student();    //無參構造函數
21     Student(int);
22     Student(string , string);  //帶參構造
23     void Setage(int val)   //簡單的函數封裝,確保年齡的有效性
24     {
25         if (val < 0)
26         {
27             _age = 18;
28         }else
29         {
30             _age = val;
31         }
32     }
33 private:          //私有成員
34     string _name;
35     string _desc;
36     int _age;
37 
38 };
39 //創建三個對象
40 Student stu1;
41 Student stu2(24);
42 Student stu3("張三" , "帥帥氣氣");  
43 
44 int main(int argc , char **argv)
45 {
46          
47      return 0;
48 }                                                  
49 
50 Student::Student()
51 {
52     cout << "默認構造"  << endl;
53 }
54 
55 Student::Student(int age)
56 {
57     Setage(age);
58     cout << "調用帶參構造:Student(int age)" << end   l;
59 }
60 
61 Student::Student(string name , string desc)
62 {
63      _name = name;
64      _desc = desc;
65      cout << "調用帶參構造:Student(string name , s   tring desc)" << endl;
66 }                                                 

 看完代碼你應該就大致的理解構造函數的作用了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章