C++ 构造函数

C++中的构造函数可以分为4类:

  1. 无参构造函数
  2. 参数构造函数
  3. 拷贝构造函数
  4. 移动构造函数(move和右值引用)
  5. 委托构造函数
  6. 转换构造函数
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值