C++

C++语法系列之13--拷贝构造函数总结

2018-04-15  本文已影响0人  hello12qwerz

1 拷贝构造函数/赋值运算符

一个问题:什么时候会调用拷贝构造函数和赋值运算符?
总结如下:
如下场景会调用复制构造函数:
1)用本类一个已经存在的对象去构造另一个新的对象
Copy a;//调用默认构造函数
Copy b(a);//调用拷贝构造函数
2)当函数的形参是类的对象(注意是对象,不是引用)时,会调用拷贝构造函数;
下面代码中的getCopy()由于形参为对象,会调用拷贝构造函数将实参的值传递给形参。
下面代码中的getCopy1()由于形参为引用,不会调用拷贝构造函数。而只是将引用从实参传递给形参。
3)当函数的返回值是对象(注意不是引用)时,此时会隐式的调用拷贝构造函数构造一个临时的对象,并传给函数的返回处。
下面代码中的getCopy()由于直接返回对象Copy,会调用拷贝构造函数。
下面代码中的getCopy1()由于返回的是引用Copy,不会调用拷贝构造函数。

class Copy {
public:
    Copy() {
        cout <<"default ctor" << endl;
        mInt = -1;
    }
    Copy(const Copy& src) {
        mInt = src.mInt;
        cout <<"copy ctor mInt = " << mInt << endl;
    }
    int getInt(const Copy src) {
        cout <<"getInt" << endl;
        return src.mInt;
    }
    
    Copy getCopy(const Copy src) {
        cout <<"getCopy" << endl;
        return src;
    }
    
    Copy getCopy1(const Copy& src) {
        cout <<"getCopy use ref" << endl;
        return src;
    }
    
    Copy& operator=(const Copy& rhs) {
        cout << "operator=" << endl;
        if (this == &rhs) {
            return *this;
        }
        
        this->setInt(rhs.getInt());
        return *this;
    }
    
public:
    void setInt(int i) {
        mInt = i;
    }
    int getInt() const {
        return mInt;
    }
private:
    int mInt;
};

int main(int argc, const char * argv[]) {
    Copy copy0;//调用默认构造函数
    Copy copy1(copy0);//调用拷贝构造函数
    cout << "----next1-----" << endl << endl;
    
    int a = copy0.getInt(copy0);//实参传递给形参时会调用拷贝构造函数
    
    cout << "----next2-----" << endl << endl;
    
    Copy c = copy0.getCopy(copy0);//实参传递给形参时会调用
    拷贝函数,同时返回对象时,也会调用拷贝构造函数
    cout << "----next3-----" << endl << endl;
    Copy d = copy0.getCopy1(copy0);//实参传递给形参时由于是引用,不会调用构造函数,但是返回的是Copy对象,会调用拷贝构造函数
    
    cout << "----next4-----" << endl << endl;
    Copy e = d;//等同于Copy e(d),此时只会调用拷贝构造函数
    
    cout << "----next5-----" << endl << endl;
    Copy f;//调用默认构造函数
    f = d;//注意调用的是复制运算符,而不是拷贝构造函数。拷贝构造函数只会在初始化的时候才会调用
}

运行结果为:

default ctor
copy ctor mInt = -1
----next1-----

copy ctor mInt = -1
getInt
----next2-----

copy ctor mInt = -1
getCopy
copy ctor mInt = -1
----next3-----

getCopy use ref
copy ctor mInt = -1
----next4-----

copy ctor mInt = -1
----next5-----

default ctor
operator=

上一篇 下一篇

猜你喜欢

热点阅读