我需要通过基类静态变量访问派生类成员

发布于 2025-01-06 03:21:53 字数 267 浏览 3 评论 0原文

我需要通过基类变量访问派生类成员变量。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

抱猫软卧 2025-01-13 03:21:53

这种需求表明设计有缺陷。

但如果你真的坚持编写糟糕的代码,你可以直接转换回 B *

The need points to a faulty design.

But if you really insist writing bad code, you can just cast back to B *.

不一样的天空 2025-01-13 03:21:53

如果没有虚函数,你唯一能做的就是贬低它。有几种方法可以实现这一点:

  • 如果启用了 RTTI 并且父类中至少有一个虚函数,则可以使用dynamic_cast,这将让您检查转换是否成功。
  • static_cast 可以让你转换到继承树中低于你的东西,但是你失去了检查它是否成功的能力。
  • 您也可以完全将谨慎抛在脑后,使用 C 型演员。

Without virtual functions the only thing you could do is downcast it. There's a few ways to go about that:

  • You can use dynamic_cast if you have RTTI enabled AND you have at least one virtual function in the parent class, which will let you check to see if the cast succeeded or not.
  • static_cast will let you cast to something below you in your inheritance tree, but you lose the ability to check if it succeeded.
  • You could also throw caution to the wind completely and use a C-style cast.
剩一世无双 2025-01-13 03:21:53

简短的回答:你不能。因为你的编译器不知道pb是什么。它可以是A类型。但是,您可以使用dynamic_cast,它会返回B 指针,如果不可能,则返回NULL

A *pa = new B();
B *pb = dynamic_cast<B*>(pa);
if (pb) {
    pb->data = 10;
}
else {
    ...
}

无论如何,如果您需要这样做,这可能意味着您应该修改您的设计,因为向上转换不是一个好主意。但有时,你就是无法避免它。例如,当使用外部库等时。

Short answer: You cannot. Because your compiler does not know what pb is. it could be of type A. However, you an use dynamic_cast, which returns a B pointer or NULL if that is not possible.

A *pa = new B();
B *pb = dynamic_cast<B*>(pa);
if (pb) {
    pb->data = 10;
}
else {
    ...
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文