从基础对象创建派生对象时最好使用哪个:复制构造函数或赋值运算符?

时间:2017-04-04 19:09:01

标签: c++ copy-constructor assignment-operator

#include <iostream>
using namespace std;

class Base
{
    public:
        Base () {cout << "\nBase Default Ctor";}
        Base (const Base& aObj) {cout << "\nCopy Ctor";}
        Base& operator=(const Base& aObj) {cout << "\nBase assignment operator";}
        ~Base() {cout << "\nBase Destructor";}
};

class Derived : public Base
{
    public:
        Derived () {cout << "\nDerived Default Ctor";}
        Derived (const Derived& aObj) {cout << "\nDerived Copy Ctor";}
        Derived (const Base& aObj) {cout << "\nDerived Copy Ctor using Base Object";}
        Derived& operator=(const Derived& aObj) {cout << "\nDerived Assignment operator";}

        Derived& operator=(const Base& aObj) {cout << "\nDerived Assignment operator using Base Object";}
        ~Derived () {cout << "\nDerived Destructor";}

};

int main ()
{
    Base bObj, bObj1;
    Derived dObj, dObj2;
    Derived dObj1 = bObj;
    dObj2 = bObj1;
    return 0;
}

这里我使用了两种技术从基础对象创建派生对象。

  1. 复制构造函数:Derived dObj1 = bObj;

  2. 赋值运算符:使用默认构造函数创建第一个派生对象,然后将基础对象分配给派生。

  3. 哪种方法更好,为什么?

0 个答案:

没有答案