- 前言
- 一、构造函数
- 二、拷贝构造函数
- 三、析构函数
- 四、const修饰对象
- 总结
前言
各位下午好,今天我们继续来学习类吧!
一、构造函数
构造函数是类中的一个特殊而且很简单的方法,是指在类在创建对象的时候自动创建的函数,构造函数的规则:
1、构造函数的名字必须是与类的名字相同的,没有返回值,可能有参数。
2、访问的权限一般是public。
3、要注意用户是不能自己调用构造函数的,必须是创建对象的时候自己调用。
注意:若类中没有自定义构造函数的话那么在创建类的时候类会自己构建一个隐式构造函数。
4、实例化构造函数时只能调用一个构造函数。
示例:
1 #include2 using namespace std; 3 class test 4 { 5 public: 6 test() 7 { 8 cout<<"无参构造"< 13 test lishuo; 14 }
输出:
lishuo@lishuo-VMware-Virtual-Platform:~/桌面$ ./bella 无参构造
例2:
#includeusing namespace std; class test { public: test() { cout<<"无参构造"< age = a; } void show() { cout< test lishuo; test lishuo1(2); lishuo1.show(); }
输出:
lishuo@lishuo-VMware-Virtual-Platform:~/桌面$ ./bella 无参构造 2
当我们想要初始化很多成员变量的时候,我们可以利用构造函数来进行构造函数的初始化列表,用“:”符号分开,例如求长方形周长:
1 #include2 using namespace std; 3 class test 4 { 5 public: 6 test(int a,int b):length(a),width(b) 7 { 8 } 9 void show() 10 { 11 cout< 19 test lishuo(2,3); 20 lishuo.show(); 21 }
输出:
10二、拷贝构造函数
在我们创建对象的时候可以带参数,用来调用对应的带参构造函数,这个参数通常是整型、字符、或者是字符串,同样我们也可以带入一个对象,这样就会触发拷贝构造函数,拷贝构造函数格式:
类名(const 类名 &对象名){};
代码如下(示例):
1 #include2 using namespace std; 3 class test 4 { 5 public: 6 test(int a){ 7 this->age = a; 8 cout<<"constractor function"< 11 cout<<"copy function"< 15 cout< 22 test lishuo(1); 23 test lishuo1(lishuo); 24 lishuo1.show(); 25 }
输出:
constractor function copy function 1三、析构函数
析构函数主要来负责当对象已经脱离作用域后的清理工作,结构:
~类名()
没有返回值,名字必须与类名相同,没有参数,前面带~,例子:
1 #include2 using namespace std; 3 class test 4 { 5 public: 6 test(){ 7 cout<<"constractor function"< 10 cout<<"destractor"< 15 test lishuo; 16 }
输出:
constractor function destractor四、const修饰对象
我们都知道const表示常量是不可以被修改的,我们同样可以用const修饰对象使里面的值不被修改,例:
#include#include using namespace std; class test { public: int a; string name; test(const int age,const string name) { a = age; this->name = name; } void show()const { cout<<"this is const"< cout<<"this is not const"< const test lishuo(3,"haha"); lishuo.show(); test lishuo1(4,"heihei"); lishuo1.show(); lishuo.a = lishuo1.a; }
输出:
this is const 3 haha this is not const 4 heihei
当然为了让他修改我们可以加入mutable关键字(感觉很二比),比如
mutable int a;总结
今天的类就学习到这里吧,明天继续!



