在 C++ 中向字符串 class 添加函数

Adding functions to string class in c++

我正在使用最新的 gcc 编译器。因此我的代码可以执行 to_String() 和 stoi() 但不幸的是,我试图在其中编译我的代码的平台有一个更早的平台,我想将这两个函数添加到字符串 class因此我可以在我的代码中使用它们而无需任何 problem.This 是我得到的每个错误示例之一。

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;

这两个函数不是“字符串 class”的一部分。您所需要的只是使用 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 一起编译。