![](/img/trans.png)
[英]How to access parent class's data member from child class, when both parent and child have the same name for the dat member
[英]How to access child class's datamember when both base and child class have same object name but different types. in C++
struct BaseType
{
int x1;
float x2;
};
struct ChildType
{
int y1;
float y2;
};
Class Base
{
BaseType obj;
void funcBase(BaseType **ptr)
{
*ptr = &obj; // When this assignment happens ofcourse obj is of the BaseType as the LHS ptr is pointing to a BaseType
Now I want to write a C++ equivalent code of the following 2 algorithmic statements,
BaseType's obj.x1 = ChildTypes's obj.y1;
BaseType's obj.x2 = ChildTypes's.obj.y1;
}
};
class Child :: public Base
{
ChildType obj;
};
我从基础访问儿童的obj.y1并将其分配给基础的obj.x1。
但是记住在基和子对象名是相同的“ obj”的1件事。
任何人都可以在这方面帮助我。 谢谢。
您的问题有些含糊,但是从我的搜集中可以得出以下信息:
ChildType* child = dynamic_cast<ChildType*>( &obj );
现在child
指向obj
,就好像它是ChildType
类型ChildType
,假设ChildType
成功。
编辑:我应该提一下,如果更好的设计可以替代它,则应避免像这样的类型转换。 也许您应该在这里重新考虑一下总体设计。
EDIT2:鉴于您最近的编辑,这是示例代码的一个更具体的块:
ChildType* child = dynamic_cast<ChildType*>( &obj );
obj.x1 = child->y1;
obj.x2 = child->y2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.