初始化列表中基类构造函数调用派生类函数

M7Heaven M7Heaven 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#include <iostream>

using std::cout;
using std::endl;

class Base
{
public:
Base(int para)
{
a = para;
cout << "Base::a = " << a << endl;
}
private:
int a;
};

class Derive : public Base
{
public:
int foo()
{
cout << "Derived::foo() return 0" << endl;
return 0;
}
Derive() : Base(foo()) {}
};

class Derive2 : public Base
{
public:
int foo()
{
cout << "Derive2::foo() return " << a << endl;
return a;
}
Derive2() : a(0), Base(foo()) {}
private:
int a;
};

int main(void)
{
Derive cld;
Derive2 cld2;
//Base *bptr = new Derive;
//bptr->foo(); //error: Base has no member named foo


return 0;
}


问题:
g++编译器进行编译没有报错,能执行
为什么Base能调用派生类定义的函数foo()进行初始化,base初始化的时候
派生类部分不是还不存在吗,怎么能调用foo(),而且foo()中还有派生类中才声明的变量a

请各位解释解释~
...全文

相关推荐

评论 11
收藏 已收藏
分享
返回顶部
M7Heaven
C++ 语言 65,214 成员 250,514 内容