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 }                                                 

 看完代码你应该就大致的理解构造函数的作用了。

原文地址:https://www.cnblogs.com/tanshengjiang/p/13330425.html