拷贝构造函数(copy constructor)

拷贝构造函数是指将已存在的该类的一个对象通过引用作为构造函数的参数进行传递,从而达到构造函数的目的。一般地存在拷贝构造函数的同时也会有其他的构造函数存在,例如:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct Complex{
    double re;
    double im;
    Complex(double re = 0, double im = 0){  //此处的re=0,im=0是指当构造函数时无参数传递下来的时候re和im值默认为0
        this->re = re;
        this->im = im;
        cout << "构造函数Complex(double, double)\n";
    }

    Complex(const Complex& z){  //拷贝构造函数
        re = z.re;
        im = z.im;
        cout << "调用拷贝构造函数Complex(const Complex&)\n";
    }

    string text(){
        stringstream ss;
        ss << re << " + " <<im << "j" <<endl;
        return ss.str();
    }
};

int main(){
    Complex a(1.0, 2.0); //通过构造函数产生类的对象z1
    cout << "a = " << a.text();
    Complex b{3.0, 4.0}; //构造函数的另一种写法
    cout << "b = " << b.text();
    Complex c = {5.0, 6.0}; //构造函数的另一种写法
    cout << "c = " << c.text();
    Complex d(a); //通过拷贝构造函数产生类的对象z2
    cout << "d = " << d.text();
    Complex e{b}; //拷贝构造函数的另一种写法
    cout << "e = " << e.text();
    Complex f = c; //拷贝构造函数的另一种写法
    cout << "f = " << f.text();
}

输出结果:

如有错误,欢迎大家批评与指正!

猜你喜欢

转载自blog.csdn.net/WJ_SHI/article/details/82223625
今日推荐