簡體   English   中英

復制構造函數,operator= 在子 class

[英]copy constructor, operator= in a child class

我想創建一個operator=和復制構造函數,以便在繼承的 class 中調用。

對於普通對象,它可以正常工作,但是當我嘗試使用指針調用operator=時,它只是在復制 object 地址。

所以我的問題是,我怎樣才能用指針調用這些方法?

#include <iostream>

// base class
class a {     
public:
    //constructors
    a(): x(0), y(1), z(0){ std::cout << "no parameter constructor A\n"; }
    a(int a, int b, int c) :x(a), y(b), z(c){ std::cout << "parameter constructor A\n"; }
    a(const a& ob):x(ob.x), y(ob.y), z(ob.z)
    {
        std::cout << "copy constructor A\n";
    }
    //operator
    a& operator=(const a& obj) 
    {
        if (this != &obj)
        {
            x = obj.x;
            y = obj.y;
            z = obj.z;
        }
        std::cout << "operator = A\n";
        return *this;   
    }
protected:
    int x, y, z;
};

//child class
class b : public a
{
public:
    //constructors
    b() : p(0){ std::cout << "no parameter constructor B\n"; }
    b(int X, int Y, int Z, int B) : a(X, Y, Z), p(B) { std::cout << "parameter constructor B\n"; }
    b(const b& obj) :p(obj.p), a(obj)
    {
        std::cout << "copy constructor B\n";
    }
    //operator =
    b& operator=(const b &obj)
    {
        if (this != &obj)
        {
            p = obj.p;
            &a::operator=(obj);
        }
        std::cout << "operator = B\n";
            return *this;
    }
private:
    int p;
};

int main()
{
    b obj0(4, 8, 16, 32);
    b obj1(obj0);   // copy constructor
    b obj2;
    obj2 = obj1;    // operator =
    std::cout << std::endl << std::endl;
    std::cout << "for pointers:\n\n";
    a* obj3 = new b(4, 8, 16, 32);
    a* obj4(obj3);
    obj4 = obj3;
    return 0;
}

輸出

使用指針(或引用)的目的之一是避免需要創建 object 的副本。 將指針傳遞給 object 允許接收器參考和操作原始 object。

如果您希望指針接收新的 object,那么您將使用new

在您的示例中處理多態性時,您可能需要一個虛擬方法來創建正確的克隆(有時稱為深拷貝)。

class a {
    //...
    virtual a * clone () const = 0;
};

class b : public a {
    //...
    b * clone () const {
        return new b(*this);
    }
};

//...
    a *obj4 = obj3->clone();
//...

我們利用b *是 a a *的協變返回類型,因此b::clone()可以返回 a b * ,但是a::clone()可以使用b::clone()作為覆蓋並且仍然返回a *

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM