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

时间:2015-10-10 13:20:24

标签: c++ class object initialization

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

#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”尚未初始化。

要完成任务,我不确定如何使用他们给我的代码。 谢谢! :)

2 个答案:

答案 0 :(得分:1)

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

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

然后

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

并且不需要

Foo fooObj(7)

答案 1 :(得分:0)

由于idprotected,您可以在Bar中访问它。