c++ - 将已经初始化的基类分配给派生类
问题描述
所以我开始涉足基类和派生类,然而,现在我开始涉足它似乎我已经碰壁了。基本上,我想要做的是将已经初始化的基类分配给派生类。这样做的原因是我想在派生类的函数中访问所述基类的一些变量。
我想出了以下方法:
class Bar
{
public:
int Example = 16;
};
class Foo : public Bar
{
public:
Bar* BarInstance;
Foo(Bar* ClassInstance) : BarInstance(ClassInstance)
{
}
int GetExample()
{
return BarInstance->Example; // Seems to work fine
}
};
这似乎工作正常,但是我想让这更容易,并像这样访问它:
Foo* FooInstance = new Foo(this) // Where this is an instance of bar
int Output = FooInstance->Example; // Expected output is 16 (see above snippet of code)
这可能吗?我记得读过一个与此类似的问题,不幸的是我无法再次找到它。任何帮助表示赞赏!
解决方案
只需这样做:
class Bar
{
public:
int Example = 16;
};
class Foo : public Bar
{
public:
};
Foo* FooInstance = new Foo();
int Output = FooInstance->Example;
由于多态性,上面的代码片段可以编译并且工作得很好。在网上看到
Foo
already has everything that Bar
has, because Foo
is a Bar
. Every Foo
object initializes and stores a Bar
object internally, and you have access to all of it's public
and protected
members via this
pointer (it's also possible to access them implictly, without mentioning this
- just like members of your own class).
You were trying to reinvent the wheel and recreate the polymorphism mechanism, without using the in-built polymorphism mechanism. While this is entirely possible, it's compilers' job, not yours (fortunately!)
推荐阅读
- django - Django - 从相关表中获取一个附加字段
- reactjs - 是否可以在 onChange 事件中获取输入的值
- python - for循环中的问题(python)
- python - 如何解决 OSError: [Errno 22] Invalid argument:
- sql-server - 等级和日期变化大小写表达式
- python - 重塑 pyspark 数据框以显示项目交互的移动窗口
- android - 膨胀菜单上的 ResourceNotFoundException
- kubernetes - 使 pod 能够控制 Kubernetes 中的另一个部署需要什么?
- node.js - 发出预检复杂 CORS 请求时,在标头中包含什么?
- java - Spring 请求映射 - 将所有 GET 请求映射到唯一的端点