簡體   English   中英

在子類中使用父類的對象。 您是否需要將對象作為類構造函數傳遞?

[英]Using an object of a parent class within a child class. Do you need to pass the object as a class constructor?

這很可能是一個重復的問題,但是我一直無法找到解決此問題的最佳方法。

我有一個父類,它創建一個對象,該對象具有對該對象進行操作的有用方法。 然后,我想創建一個子類,該子類通過引用獲取父類的對象,並具有對其進行操作的其他方法。

我想知道如何最好地解決這個問題? 我是否應該將指向父類對象的指針作為子類的構造函數傳遞?

我想做的是:

class obj_parent{
    initializes object
    virtual void method_1
    virtual void method_2
}

class operation: public obj_parent {
    void opertation_method_1(*object)
    void opertation_method_2(object)
}

如果對父類和子類進行模板化,還會有什么區別?

我沒有找到關於該主題的一些參考資料,但我的問題沒有完全解決,但可能很有用。 將對象傳遞給類構造函數 將模板類的對象傳遞給另一個類的構造函數

好的,下面的示例正是您想要做的:子級通過引用修改父級對象的實例。 父級擁有一個int。 是的,在現實生活中,一個對象通常會具有多個成員變量,但這只是一個示例。

class parentInt {
public:
    int memberNumber;
    parentInt(int number) {
        memberNumber = number;
    }
    parentInt() {
        memberNumber = 0;
    }
};

class childInt : public parentInt {
public:
    parentInt& mReferenceToParentObject;
    childInt(parentInt& referenceToParentObject) :mReferenceToParentObject(referenceToParentObject) {}
    void addOne() {
        mReferenceToParentObject.memberNumber++;
    }
    void subtractOne() {
        mReferenceToParentObject.memberNumber--;
    }
};


int main()
{
    parentInt p(5); //parent int is 5
    childInt c(p); //child int is a reference to parent
    c.addOne();  // parent's memberNumber is now 6 because the child modified the parent through the reference
    c.subtractOne();  // parent's memberNumber is now 5 because the child modified the parent through the reference
}

如果您這樣做是為了解決方程式系統(原始問題中未提及,請參見評論),則將上面的memberNumber替換為向量的矢量來表示2D矩陣,然后將addOne更改為類似Gaussian Elimination的算法來求解系統方程。

暫無
暫無

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

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