【拷贝构造函数】

来源:百度知道 编辑:UC知道 时间:2024/06/28 15:52:58
point p
point p1(p); //A
point p2=p; //B
p2=p; //C
1、A,B行都会调用拷贝构造函数。C行不是初始化,只是赋值,所以不调用,
这样理解对吗?
2、所有的构造函数(包括缺省,拷贝),都是在创建对象的时候,就是定义时调用。。。。对吗?

完全正确,给个例子你加深理解。
#include <iostream>
using namespace std;

class point
{
public:
point(int xp=0, int yp=0) : x(xp), y(yp)
{
cout << "This line is from default constructor." << endl;
}
point(const point &rhs)
{
cout << "This line is from copy constructor." << endl;
x = rhs.x;
y = rhs.y;
}
point &operator=(const point &rhs)
{
cout << "Thie line is from operator=."<< endl;
if (this == &rhs)
return *this;

x = rhs.x;
y = rhs.y;
return *this;
}

private:
int x, y;
};

void main()
{
point p;
point p1(p); //A
point p2=p; //B
p2=p; //C
}

没错,你的理解是正确的!