所以我想知道是否真的可以从继承的类对象访问基类的构造函数?像这样的东西:
#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)
关于c++ - 是否可以从继承类对象访问基类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054464/