程序设计MOOC 奇怪的类复制

#include <iostream>
using namespace std;
class Sample
{
public:
    int v;
    Sample( const int vv = 0 )
    {
        v = vv;
    }
    Sample( const Sample & a )
    {
        v = a.v + 2;
    }
};
void PrintAndDouble(Sample o)
{
    cout << o.v;
    cout << endl;
}
int main()
{
    Sample a(5);
    Sample b = a;
    PrintAndDouble(b);
    Sample c = 20;
    PrintAndDouble(c);
    Sample d;
    d = a;
    cout << d.v;
    return 0;
}
当用一个对象去初始另一个对象时或者对象作为函数参数时,会调用复制构造函数。所以复制构造函数不要瞎写。

猜你喜欢

转载自blog.csdn.net/xutian_curry/article/details/80472169