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;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章