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