-1
class B_mem { 
    public: 
    int b_var; 
}; 
class D_mem : public B_mem { 
    public: 
    int d_var; 
}; 

class B { 
    public: 
    B_mem b_member; 
}; 

class D : public B { 
    public: 
    D_mem d_member; 
}; 


int main() { 
    D derived; 
    D_mem dmem; 
    dmem.b_var = 2; 
    dmem.d_var = 3; 
    B* b_ptr = &derived; 
    std::cout << b_ptr->b_member.b_var; // Doesn't print 2 
} 

我怎樣才能構建的類,使得當我設置/更新D_mem,它將自動設置/更新B_mem(如果相關)?在上面的示例中,我創建了D並填充了D_mem,但隨後使用類型爲B的指針訪問了D。我希望能夠通過B_mem訪問D中的D_mem的基類成員。C++聯基類成員派生類成員

我想知道是否有多態性的東西,複製構造函數,或設置功能,這將允許我做到這一點,而不必手動保持D_mem和B_mem一致。

+0

'dmem'和'derived.d_member'是不同的對象。 – drescherjm

+0

啊是的!我想在定義'dmem'後添加'derived.d_member = dmem'。即使使用修復程序,您仍然會遇到同樣的問題。 – LexTron

回答

2

std::cout << b_ptr->b_member.b_var; // Doesn't print 2

當然事實並非如此。

線條

D_mem dmem; 
dmem.b_var = 2; 
dmem.d_var = 3; 

沒有做任何改變derived成員變量。他們仍處於未初始化狀態。

您可以使用:

int main() { 
    D derived; 

    D_mem& dmem = derived.d_member; // Get a reference to an existing object 
    dmem.b_var = 2;     // Modify the referenced object 
    dmem.d_var = 3; 

    // That still doesn't change b_member. 
    // Need to update it too. 
    derived.b_member.b_var = 2; 

    B* b_ptr = &derived; 
    std::cout << b_ptr->b_member.b_var; // Doesn't print 2 
} 

int main() { 
    D derived; 
    D_mem dmem; 
    dmem.b_var = 2; 
    dmem.d_var = 3; 

    derived.d_member = dmem; // Set the value of derived. 
    derived.b_member = dmem; 

    B* b_ptr = &derived; 
    std::cout << b_ptr->b_member.b_var; // Doesn't print 2 
} 

回覆:

我想知道是否有一些與多態,拷貝構造函數,或者設置的功能,將允許我這樣做,而不必手動保持D_memB_mem一致。

你可以做,如果你提供照顧的那些細節,使成員變量私有成員函數,但是因爲你有兩個基本的DB_mem情況下,它就會變得混亂。

如果使用指針而不是對象,代碼會變得更簡單,更容易維護。

這裏是一個示例實現:

#include <iostream> 
#include <memory> 

class B_mem { 
    public: 
     int b_var; 
     virtual ~B_mem() {} 
}; 

class D_mem : public B_mem { 
    public: 
     int d_var; 
}; 

class B { 
    protected: 
     std::shared_ptr<B_mem> b_member; 

    public: 

     B(std::shared_ptr<B_mem> member) : b_member(member){} 
     virtual ~B() {} 

     virtual B_mem& getMember() = 0; 

     virtual B_mem const& getMember() const = 0; 
}; 

class D : public B { 

    public: 

     D() : B(std::shared_ptr<B_mem>(new D_mem)){} 

     D_mem& getMember() 
     { 
     return *(std::dynamic_pointer_cast<D_mem>(b_member)); 
     } 

     D_mem const& getMember() const 
     { 
     return *(std::dynamic_pointer_cast<D_mem>(b_member)); 
     } 
}; 


int main() { 
    D derived; 

    derived.getMember().b_var = 2; 
    derived.getMember().d_var = 3; 

    B* b_ptr = &derived; 
    std::cout << b_ptr->getMember().b_var << std::endl; 
} 

輸出:

2 
相關問題