拷贝构造函数被调用的时机:
1. 当用类的一个对象去初始化该类的另一个对象(或引用)时系统自动调用拷贝构造函数实现拷贝赋值。
2. 若函数的形参为类对象,调用函数时,实参赋值给形参,系统自动调用拷贝构造函数。
3. 当函数的返回值是类对象时,系统自动调用拷贝构造函数。
下面给出一个例子:
- #include <iostream>
- using namespace std;
-
- class Point
- {
- public:
- Point(int xx=0,int yy=0)
- {
- X=xx;
- Y=yy;
- }
- Point(Point& p);
- int GetX() {return X;}
- int GetY() {return Y;}
- private:
- int X,Y;
- static int count;
- };
-
- Point::Point(Point &p)
- {
- X = p.X;
- Y = p.Y;
- count++;
- cout << "拷贝构造函数被调用, " << "count:"<< count << endl;
- }
-
- void fun1(Point p)
- {
- cout<<p.GetX()<<endl;
- }
-
- Point fun2()
- {
- Point A(3,4);
- //调用拷贝构造函数
- return A;
- }
-
-
- int Point::count = 0;
-
- void main(void)
- {
- Point A(1,2);
- // 当用类的一个对象去初始化该类的另一个对象时系统自动调用拷贝构造函数实现拷贝赋值。
- Point B(A); //拷贝构造函数被调用
- cout<<B.GetX()<<endl;
-
- // 若函数的形参为类对象,调用函数时,实参赋值给形参,系统自动调用拷贝构造函数
- fun1(A); //调用拷贝构造函数
-
- // 当函数的返回值是类对象时,系统自动调用拷贝构造函数。
- B = fun2();
- cout<<B.GetX()<<endl;
-
- // 调用2次拷贝构造函数,第一处是在fun2()中的return A,第二处是将fun2的返回值初始化引用ref时。
- Point & ref = fun2();
- cout<<ref.GetX()<<endl;
-
- }
|