首页 > 解决方案 > 将已经初始化的基类分配给派生类

问题描述

所以我开始涉足基类和派生类,然而,现在我开始涉足它似乎我已经碰壁了。基本上,我想要做的是将已经初始化的基类分配给派生类。这样做的原因是我想在派生类的函数中访问所述基类的一些变量。

我想出了以下方法:

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)

这可能吗?我记得读过一个与此类似的问题,不幸的是我无法再次找到它。任何帮助表示赞赏!

标签: c++

解决方案


只需这样做:

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!)


推荐阅读