《C++程序设计POJ》《WEEK3 类和对象进阶》

复制构造函数

Complex(const Complex & c)

X::X(X&)

X::X(const X &)

二者选一,后者能以常量对象作为参数

复制构造函数起作用的三种情况:

1)当用一个对象去初始化同类的另一个对象时
Complex c2(c1);
Complex c2 = c1; //初始化语句,非赋值语句

Complex c2(c1);

2)如果某函数有一个参数是类 A 的对象, 那么该函数被调用时,类A的复制构造函数将被调用。

class A

{

public:

A() { };

A( A & a)

{

cout << "Copy constructor called" <<endl;

}

};

#include<iostream>
#include<cstdio>

using namespace std;

#if 0
/*当用一个对象去初始化同类的另一个对象时。*/
class Complex {
public:
    double real, imag;
    Complex() {}
    Complex(const Complex &c) {
        real = c.real;
        imag = c.imag;
        cout << "copy constructor called";
    }

};
int main()
{

    Complex c1;
    Complex c2(c1);
    while (1);
}

#endif
/*如果某函数有一个参数是类 A 的对象,
那么该函数被调用时,类A的复制构造函数将被调用*/
#if 0
class A
{
public:
    A() {};
    A(A&a) {
        cout << "Copy constructor called" << endl;
    }
};
void Func(A a1) {}
int main()
{
    A a2;
    Func(a2);
    while (1);
    return 0;
}
#endif
/*如果函数的返回值是类A的对象时,则函数返回时,
A的复制构造函数被调*/
class A
{
public:
    int v;
    A(int n)
    {
        v = n;
    }
    A(const A & a)
    {
        v = a.v;
        cout << "Copy constructor called" << endl;
    }
};
A Func()
{
    A b(4);
    return b;
}
int main()
{
    cout << Func().v << endl;
    while (1);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/focus-z/p/10982566.html