C/C++默认生成的几个函数s

一、关键词

  • 类/结构体默认生成。
  • 拷贝/移动 + 构造/赋值 = 组合不同方式有4种,除默认、析构,共计6种。
  • 在使用时:拷贝/移动 + 赋值的,都是定义和赋值分开;拷贝/移动 + 构造的,都是定义和赋值一起。

二:知识点

  1. 默认构造函数
    Student():age(0){};
  2. 拷贝构造函数
    Student(const Student& item) : age(item.age){};
  3. 析构函数
    ~Student():age(0){}
  4. 拷贝赋值运算符
Student& ooperator=(const Student& item){
	if(this == &item){return *this;}
	age = item.age;
	return *this;
  1. 移动构造函数
Student(Student&& item){
	age = item.age;
	item.age = 0;
}
  1. 移动赋值运算符
Student& operator=(Student&& item){
	if(this == &item)return *this;
	age = item.age;
	item.age = 0;
	return *this;
}

三、实际运用

//默认构造函数
Student s;

//拷贝构造函数
Student s2 = s;

//拷贝赋值运算符
Student s2;
s2 = s;

//移动构造函数
Student s3 = std::move(s);

//移动赋值运算符
Student s4;
s4 = std::move(s);

posted @ 2024-07-26 10:13  Labant  阅读(14)  评论(0)    收藏  举报