C++-------拷贝构造函数

简单的默认拷贝构造函数(相当于不写出来默认存在)
#include <iostream>
using namespace std;
class Test
{
public:
    Test(int aa, int bb) :x(aa), y(bb) {}
    Test() {}
    void show()
    {
        cout << x << " " << y << endl;
    }
    Test(const Test &another)
    {
        x = another.x;
        y = another.y;
    }
private:
    int x;
    int y;
};

int main()
{
    Test t1(100, 200);
    //t1.show();
    Test t2(t1);
        //Test t2=t1;  //同理,调用拷贝构造函数
    t2.show();
    system("pause");
    return 0;
}

注意:构造函数是对象初始化的时候调用
     而Test t3;
       t3=t1;   并没有调用构造函数,而是t3的赋值操作符函数,即运算符重载函数
需要在类中定义运算符重载函数:

void operator=(const Test &another)
{
x = another.x;
y = another.y;
}


原文地址:https://www.cnblogs.com/god-for-speed/p/10910050.html