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

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

本文关键字:对象 访问 基类 构造函数 是否 继承      更新时间:2023-10-16

所以我想知道是否实际上可以从继承的类对象访问基类的构造函数?比如:

#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'没有初始化。

有一个任务要做,我不确定如何使用他们给我的代码。谢谢!:)

首先创建与基类匹配的构造函数:

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

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

和不需要

Foo fooObj(7)

因为idprotected,所以可以在Bar中访问它