#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;
}
这里我使用了两种技术从基础对象创建派生对象。
复制构造函数:Derived dObj1 = bObj;
赋值运算符:使用默认构造函数创建第一个派生对象,然后将基础对象分配给派生。
哪种方法更好,为什么?