什么时候调用拷贝构造函数什么时候调用拷贝构造函数
https://blog.csdn.net/veryday_code/article/details/7982996?utm_source=blogxgwz7
https://blog.csdn.net/qq_16993255/article/details/78652960
以下几种情况会调用拷贝构造函数
1. 以一个对象初始化另一个对象
2. 函数以某个对象为参数
3. 函数返回某个对象
4. 初始化序列式容器的元素
2.
void test2()
{
Test t1(1,2);
Test t2;
t2=t1;//调用的不是拷贝构造函数,调用的是=号操作符,也能够完成将t1的值给t2,但是不是调用t2的拷贝构造函数
}
另外以下程序 points[i] = pointsArray1.points[i]; 这一行并不会触发 拷贝构造函数。调用的是 = 赋值运算符。赋值运算符完成
两个对象的复制。
//6_21.cpp
#include
#include
#include
#include
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<"Point Default Constructor called."<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<< "Point Constructor with two arguments called."<<endl;
}
Point(const Point & point){
x= point.x;
y = point.y;
cout<< "Point copy Constructor called."<<endl;
}
~Point() { cout<<"Point Destructor called."<<endl; }
int getX() const { return x; }
评论0