You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现三层类继承触发expected class-name错误如何解决

问题原因

你遇到的编译报错核心原因是子类头文件未引入父类的头文件,编译器处理继承声明时无法识别父类的类名,因此抛出error: expected class-name before '{' token错误:

  • Mother.h中声明继承自GrandMother,但文件内没有引入GrandMother.h,编译器无法识别GrandMother类名
  • Daughter.h中声明继承自Mother,但文件内没有引入Mother.h,编译器无法识别Mother类名

修复方案

仅需要修改两个子类的头文件,补充对应父类头文件的引入即可:

修改后的Mother.h

#ifndef MOTHER_H
#define MOTHER_H
// 补充引入父类头文件
#include "GrandMother.h"

class Mother: public GrandMother
{
    public:
        Mother();
        ~Mother();
};

#endif // MOTHER_H

修改后的Daughter.h

#ifndef DAUGHTER_H
#define DAUGHTER_H
// 补充引入父类头文件
#include "Mother.h"

class Daughter: public Mother
{
    public:
        Daughter();
        ~Daughter();
};

#endif // DAUGHTER_H

额外优化建议(非必须,不影响编译)

所有cpp文件中不需要引入和当前实现无关的头文件,比如GrandMother.cpp仅需要引入<iostream>和GrandMother.h即可,无需引入Mother.h、Daughter.h,冗余的头文件引入会拖慢编译速度。

修改完成后编译运行,输出结果会符合C++继承机制的构造/析构顺序:

Grand Mother Constructor!!
Mother Constructor!!
Daughter Constructor!!
Daughter Deconstroctor
Mother Deconstroctor
Grand Mother Deconstroctor

内容的提问来源于stack exchange,提问作者Yash Malhotra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:57:04