C++的构造函数和赋值运算符们/移动构造函数

C++都有哪些构造函数?普通的构造函数、拷贝构造函数、移动构造函数、委托构造函数。

#include <iostream>
using namespace std;

class A
{
public:
	int x, y;
	//默认构造函数
	A() {}
	//带参数的构造函数
	A(int x) : x(x) {
		cout << "constructor" << endl;
	}
	//拷贝构造函数
	A(const A& a) : x(a.x), y(a.y) {
		cout << "copy constructor" << endl;
	}
	//赋值运算符
	A& operator=(const A& a) {
		cout << "operator = " << endl;
		this->x = a.x;
		this->y = a.y;
		return *this;
	}
	//委托构造函数
	A(int x_, int y_) : A(x_) {
		cout << "delegating constructor" << endl;
		this->y = y_;
	}
	//移动构造函数
	A(A&& a) : x(a.x), y(a.y) {
		cout << "move constructor" << endl;
	}
	//移动赋值运算符
	A& operator=(A&& a) {
		cout << "move operator = " << endl;
		this->x = a.x;
		this->y = a.y;
		return *this;
	}
	//析构函数
	~A() {}
};

int main()
{
	cout << "-------------------------1-------------------------" << endl;
	A a(1);
	cout << "-------------------------2-------------------------" << endl;
	A b = a;
	cout << "-------------------------3-------------------------" << endl;
	A c(a);
	cout << "-------------------------4-------------------------" << endl;
	b = a;
	cout << "-------------------------5-------------------------" << endl;
	A d = A(1);
	cout << "-------------------------6-------------------------" << endl;
	A e = std::move(a);
	cout << "-------------------------7-------------------------" << endl;
	d = A(1);
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值