是否可以从继承的 class 对象访问基础 class 的构造函数?

Is it possible to access the constructor of the base class from the inherited class object?

所以我想知道是否真的可以从继承的 classes 对象访问基础 class 的构造函数?类似于:

#include <iostream>

class Foo
{
public:
    Foo(int i)
    {
        id = i;
    }
protected:
    int id;
};

class Bar: public Foo
{
public:
    void barFunc()
    {
        if (id>0)
        {
            std::cout << "Bar stuff" << std::endl;
        }
        else
        {
            std::cout << "Other Bar stuff" << std::endl;
        }
    }
};

int main()
{
    Foo fooObj(7);
    Bar b; //is it possible to access 'id' in Bar whilst initializing 'id' in Foo?
    b.barFunc();
}

如果我只是 运行 barFunc() 对象 b 将表现得好像 'id' 还没有被初始化。

有作业要做,但我不确定如何使用他们给我的代码。 谢谢! :)

因为 idprotected 您可以在 Bar.

中访问它

首先创建匹配基础的构造函数class:

Bar(int i) : Foo(i) { }

然后

Bar b(1);
b.barFunc();

不需要

Foo fooObj(7)