#include <iostream>
using namespace std;
class Coordinate {
public:
Coordinate(int x = 0, int y = 0) {
X = x;
Y = y;
cout << "Constructor Object. \n";
}
/*Coordinate(Coordinate& p) {
X = p.X;
//X = p.getX(); // ok
Y = p.Y;
cout << "Copy_constructor called." << endl;
}*/
Coordinate(const Coordinate& p) { // 复制构造函数 or 拷贝构造函数
X = p.X; // p.X里X是private ???
//X = p.getX(); // error
Y = p.Y;
cout << "Copy_constructor called." << endl;
}
~Coordinate() {
cout << X << "," << Y << " Object destroyed." << endl;
}
int getX() { return X; }
int getY() { return Y; }
protected:
private:
int X;
int Y;
};
//赋值构造函数的第三个应用场景:实参对象传给形参对象时调用copy构造函数
void f(Coordinate p) { // 实参对象传给形参对象时调用copy构造函数
cout << "Function: " << p.getX() << "," << p.getY() << endl;
}
void test() {
Coordinate A(1, 2);
f(A);
}
void main() {
test();
system("pause");
}
C++拷贝构造函数的应用场景Demo03
于 2022-08-01 21:56:19 首次发布