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_mem
和B_mem
一致。
你可以做,如果你提供照顧的那些細節,使成員變量私有成員函數,但是因爲你有兩個基本的D
的B_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
'dmem'和'derived.d_member'是不同的對象。 – drescherjm
啊是的!我想在定義'dmem'後添加'derived.d_member = dmem'。即使使用修復程序,您仍然會遇到同樣的問題。 – LexTron