什么是复制构造函数?
复制构造函数是一个成员函数,它使用相同类的另一个对象初始化一个对象。复制构造函数具有以下常规函数原型:
ClassName(const ClassName&old_obj);
以下是复制构造函数的一个简单示例:
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point(const Point &p1) {x = p1.x; y = p1.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
输出