【问题标题】:Adding functions to string class in c++在 C++ 中向字符串类添加函数
【发布时间】:2021-12-26 22:53:30
【问题描述】:

我正在为 gcc 使用最新的编译器。因此我的代码可以执行 to_String() 和 stoi() 但不幸的是,我试图编译我的代码的平台有一个以前的平台,我想将这两个函数添加到字符串类中,因此我可以在我的代码中使用它们没有任何问题。这是我得到的每个错误示例之一。

Cabinet.cpp:93:25: error: 'to_string' was not declared in this scope
 cout << to_string(id) << " not found"<<endl;
LabOrganizer.cpp: In member function 'void LabOrganizer::findClosest(int, int, int)':
LabOrganizer.cpp:294:38: error: 'stoi' was not declared in this scope
        cc = stoi(arr1[i].substr(1,1))-1;

【问题讨论】:

  • 你是否尝试过包含命名空间,例如std::to_string
  • @AlpE 不要做 using namespace std; 并且要包含您希望调用的函数的正确标题。
  • with 1998 gcc 你是考古学家吗?
  • “将这两个函数添加到字符串类”的唯一实用方法是使用最新的更新您的 1998 标准库和编译器。如果由于某种原因无法完成,则需要使用 1998 年的 C++ 子集编写。
  • 这些都不是std::string(或任何其他类)的成员。没有什么能阻止您实现它们,而是将它们放在您自己(或全局)的命名空间中。

标签: c++ string gcc overloading c++98


【解决方案1】:

这两个函数不是“字符串类”的一部分。您所需要的只是使用 1998 年存在的替代品:

  • 在这种情况下甚至不需要to_string 函数。您可以简单地将其更改为:

    cout << id << " not found" << endl;
    
  • 您可以将stoi 替换为atoi。如果转换失败,它不会抛出异常,但由于这是一项学校作业——你很可能并不关心这一点:

    cc = atoi(arr1[i].substr(1,1).c_str())-1;
    

如果你有很多实例的替换过于繁琐,你当然可以在一些通用的头文件中定义这些函数:

template<class T>
std::string to_string(const T &x) {
    std::ostringstream s;
    s << x;
    return s.str();
}

inline int stoi(const std::string &s) {
    // ... ignores error handling ...
    return atoi(s.c_str());
}

希望这与 1998 年的 GCC 一致。

【讨论】:

  • 你是最棒的谢谢。)
猜你喜欢
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 2010-12-13
  • 2022-01-16
  • 2023-03-17
  • 1970-01-01
  • 2013-12-21
相关资源
最近更新 更多