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.我希望能够在D到B_mem中访问D_mem的基类成员。
我想知道是否存在多态,复制构造函数或设置函数,这些函数允许我这样做,而无需手动保持D_mem和B_mem一致。
答案 0 :(得分: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_mem
和B_mem
一致。
如果您提供处理这些详细信息的成员函数并将成员变量设为私有,那么您可以这样做,因为B_mem
中基本上有两个D
实例,所以它会变得混乱。
如果使用指针而不是对象,代码将变得更简单,更容易维护。
以下是一个示例实现:
#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