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

C++自定义RomanNumeralType类使用string类型报错如何解决?

问题修复方案

你遇到的编译错误由3个语法/规则问题导致,对应修复方法如下:

  • 命名空间规则问题:C++标准库的string类型定义在std命名空间下,仅引入<string>头不足以让编译器识别string标识符。头文件不推荐直接声明using namespace std,你需要将头文件中所有的string前加std::前缀。
  • main函数结构错误:你当前代码中cin >> ans;后错误闭合了main函数的大括号,导致后续的RomanNumeralType r1(ans);定义在全局作用域,无法访问main函数内的局部变量ans。
  • 类定义缺少结束分号:C++要求类定义结束后必须在大括号后添加分号,否则会触发语法错误。

修正后代码

Header2.h

#ifndef HEADER2
#define HEADER2
#include <string>

class RomanNumeralType {
public:
    std::string romanNumeral;

    RomanNumeralType(std::string x)
    {
        romanNumeral = x;
    }

    std::string getNumeral()
    {
        return romanNumeral;
    }

    // 后续自行实现数字转换逻辑
    int getNumber(std::string numeral);
};
#endif

main.cpp

#include <iostream>
#include <iomanip>
#include "Header2.h"
#include <string>
using namespace std;

int main() {
    string ans;
    cout << "Please enter a string of Roman Numerals (M,D,C,L,X,V,I): " << endl;
    cin >> ans;

    RomanNumeralType r1(ans);
    cout << "Your original Roman Numeral was: " << r1.getNumeral() << endl;
    // 完成getNumber实现后可解除下方注释
    // cout << "Your Roman Numeral as a integer is: " << r1.getNumber(r1.getNumeral()) << endl;

    return 0;
}

完成上述修改后即可解决string无法识别的编译报错,后续可继续实现getNumber的数字转换逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 12:15:03