【问题标题】:Is it possible to access the constructor of the base class from the inherited class object?是否可以从继承的类对象中访问基类的构造函数?
【发布时间】:2015-10-10 13:20:23
【问题描述】:

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

#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 中缺少一个构造函数(添加或继承它),并在b 的声明中使用了。你必须解决这个问题。
  • 这真的编译了吗?是的,有可能,只需将成员初始化列表与 Bars 构造函数一起使用。
  • 谢谢,是的,我错过了 Bar 的构造函数,我很抱歉,是的,它有效,但我将构造函数留空,如果 id 未初始化,则未初始化,它会输出“id is not初始化”。这只是对我试图表达的内容的快速淡化,只是几行。谢谢:)

标签: c++ class object initialization


【解决方案1】:

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

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

然后

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

不需要

Foo fooObj(7)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2017-06-28
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      相关资源
      最近更新 更多