您的位置:首页 > 编程语言 > C语言/C++

C++ 拷贝构造函数和重载赋值操作符不能相互调用

2014-02-14 09:35 211 查看
拷贝构造函数调用重载赋值操作符,重载赋值操作符调用拷贝构造函数的写法都是没有意义的。

首先:

拷贝构造函数的存在意义--------是通过已有的对象构造新的对象,构造完毕后才有两个对象

重载赋值操作符的意义-----------将一个对象的值赋给另一个对象,两个对象都已经构造完毕了

拷贝构造函数----调用-----重载赋值操作符:把已有对象的值赋给一个构造中的对象,虽然这个对象的内存已经分配好了
                                                                 但是有可能导致循环调用重载赋值操作符和拷贝构造函数

重载赋值操作符---调用------拷贝构造函数:把已有对象复制并赋值给这个对象。
                                                                  导致循环调用重载赋值操作符。
总之--复制构造函数调用赋值操作符就好像正在构造的对象却用已经构造好的对象;
           赋值操作符调用复制构造函数就好像用正在构造的对象进行赋值;

例子:


例子1:拷贝构造函数调用重载赋值操作符(导致循环调用重载赋值操作符和拷贝构造函数 )

[cpp] view
plaincopy

#include <iostream>  

using namespace std;  

  

class Base {  

public:  

    Base() {cout << "Constructor invoked!" << endl;}  

    ~Base() {cout << "Destructor invoked!" << endl;}  

    Base(const Base& rhs) {  

        cout << "Copy constructor invoked!" << endl;  

        operator=(rhs); // *this = rhs;  

    }  

    Base operator=(const Base& rhs) { // 问题出在这里,返回值不是引用会调用拷贝构造函数  

        cout << "Copy assignment operator invoked!" << endl;  

        return *this;  

    }  

};  

  

int main(int argc, char** argv) {  

    cout << "Hello World C++!" << endl;  

    Base a;  

    Base b(a); // Base b = Base(a);  

    return 0;  

}  

修改后

[cpp] view
plaincopy

#include <iostream>  

using namespace std;  

  

class Base {  

public:  

    Base() {cout << "Constructor invoked!" << endl;}  

    ~Base() {cout << "Destructor invoked!" << endl;}  

    Base(const Base& rhs) {  

        cout << "Copy constructor invoked!" << endl;  

        operator=(rhs); // *this = rhs;  

    }  

    Base& operator=(const Base& rhs) { // 返回引用,可以接受  

        cout << "Copy assignment operator invoked!" << endl;  

        return *this;  

    }  

};  

  

int main(int argc, char** argv) {  

    cout << "Hello World C++!" << endl;  

    Base a;  

    Base b(a); // Base b = Base(a);  

    return 0;  

}  

这样做没有任何问题,但是破坏了拷贝构造函数的意义(不同人,可能理解不同),所以不推荐。

例子2:重载赋值操作符调用拷贝构造函数(导致循环调用重载赋值操作符 )

[cpp] view
plaincopy

#include <iostream>  

using namespace std;  

  

class Base {  

public:  

    Base() {cout << "Constructor invoked!" << endl;}  

    ~Base() {cout << "Destructor invoked!" << endl;}  

    Base(const Base& rhs) {  

        cout << "Copy constructor invoked!" << endl;  

    }  

    Base& operator=(const Base& rhs) {  

        cout << "Copy assignment operator invoked!" << endl;  

        *this = Base(rhs);  

        return *this;  

    }  

};  

  

int main(int argc, char** argv) {  

    cout << "Hello World C++!" << endl;  

    Base a;  

    Base b(a); // Base b = Base(a);  

    b = a;  

    return 0;  

}  

用法例子:

class   A;    

 A  a;  

 A  b=a;   //拷贝构造函数调用  

 //或  

 A  b(a);   //拷贝构造函数调用  

 

 A  a;  

 A  b;  

 b =a;   //赋值运算符调用  

你只需要记住,在C++语言里如下两种形式---均调用拷贝 构造函数


 String   s2(s1);  

 String   s3   =   s1;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: