C++中的构造函数可以分为4类:
- 无参构造函数
- 参数构造函数
- 拷贝构造函数
- 移动构造函数(move和右值引用)
- 委托构造函数
- 转换构造函数
#include <iostream>
using namespace std;
class Student{
public:
//1.无参构造函数,默认构造函数
Student(){
this->age = 20;
this->num = 1000;
};
//2.有参构造函数,有参数和参数列表
Student(int a, int n):age(a), num(n){};
//3.拷贝构造函数
Student(const Student& s){
this->age = s.age;
this->num = s.num;
};
//4. 移动构造函数
//移动构造函数的参数和拷贝构造函数不同,拷贝构造函数的参数是一个左值引用,但是移动构造函数的初值是一个右值引用。这意味着,移动构造函数的参数是一个右值或者将亡值的引用。也就是说,只用用一个右值,或者将亡值初始化另一个对象的时候,才会调用移动构造函数。
Student(Student &&s)
{
cout<<"移动构造函数..."<<endl;
str = NULL;
str = s.str;
s.str = NULL;
}
//5.委托构造函数
//C++11 引入了委托构造的概念,某个类型的一个构造函数可以委托同类型的另一个构造函数对对象进行初始化
Student(char ch) : Person() {
this->ch=ch;
}
//6.转换构造函数,形参是其他类型变量,且只有一个形参
Student(int r){
this->age = r;
this->num = 1002;
};
~Student(){}
public:
int age;
int num;
char ch;`
int* str;
};
int main(){
Student s1;
Student s2(18,1001);
int a = 10;
Student s3(a);
Student s4(s3);
printf("s1 age:%d, num:%d\n", s1.age, s1.num);
printf("s2 age:%d, num:%d\n", s2.age, s2.num);
printf("s3 age:%d, num:%d\n", s3.age, s3.num);
printf("s2 age:%d, num:%d\n", s4.age, s4.num);
return 0;
}