我需要通过基类静态变量访问派生类成员
我需要通过基类变量访问派生类成员变量。
Class A{
};
Class B:public A {
int data;
};
现在我需要做这样的事情
A *pb = new B()
pb->data = 10;
,但问题是我无法在没有它的情况下访问派生成员类。
是的,我知道如何让它与虚拟函数一起工作。
谢谢,我真的很感谢你的帮助。
I need to access the derived class member variable through Base class variable.
Class A{
};
Class B:public A {
int data;
};
now I need to do something like this
A *pb = new B()
pb->data = 10;
but the problem is I cannot access the Derived member class wihtout it.
and Yeah I know how to make it work with virtual functions.
Thanks, I really appreciate your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这种需求表明设计有缺陷。
但如果你真的坚持编写糟糕的代码,你可以直接转换回
B *
。The need points to a faulty design.
But if you really insist writing bad code, you can just cast back to
B *
.如果没有虚函数,你唯一能做的就是贬低它。有几种方法可以实现这一点:
Without virtual functions the only thing you could do is downcast it. There's a few ways to go about that:
简短的回答:你不能。因为你的编译器不知道
pb
是什么。它可以是A
类型。但是,您可以使用dynamic_cast
,它会返回B
指针,如果不可能,则返回NULL
。无论如何,如果您需要这样做,这可能意味着您应该修改您的设计,因为向上转换不是一个好主意。但有时,你就是无法避免它。例如,当使用外部库等时。
Short answer: You cannot. Because your compiler does not know what
pb
is. it could be of typeA
. However, you an usedynamic_cast
, which returns aB
pointer orNULL
if that is not possible.Anyhow, if you need to do that it probably means that you should revise your design as upcasting is not a good idea. Sometimes though, you just cannot avoid it. E.g. when using external libraries and such.