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

咨询:这段涉及C++继承的代码为何无法编译?

为什么这段C++继承代码无法编译?

先看你给出的代码:

class A { public: virtual string F() = 0; }; 
class B: public A { public: string F() { return "B"; } }; 
int main() { B b; A* ap = &b; cout << b.F() << ap->F(); return 0; }

这段代码编译失败主要有三个核心原因:

  • 缺少必要的头文件

    • 你使用了string类型,但没有包含<string>头文件。C++标准规定std::string的定义在<string>头文件中,不包含的话编译器无法识别这个类型。
    • 你使用了cout输出内容,cout属于标准输入输出流组件,必须包含<iostream>头文件才能正常使用。
  • 未限定std命名空间
    string和cout都是C++标准库中std命名空间下的成员,代码里直接使用它们却没指定命名空间,编译器会找不到这些标识符。解决方式有两种:

    1. 在代码开头添加using namespace std;(适合小型示例程序)
    2. 给每个标准库标识符加上std::前缀,比如std::string、std::cout

修正后的可编译代码示例:

#include <string>
#include <iostream>

using namespace std;

class A { public: virtual string F() = 0; }; 
class B: public A { public: string F() { return "B"; } }; 

int main() { 
    B b; 
    A* ap = &b; 
    cout << b.F() << ap->F(); 
    return 0; 
}

修改后代码可以正常编译运行,输出结果为BB。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:24:28