【问题标题】:I do not understand the error I am getting when trying to use a string as a function parameter我不明白尝试将字符串用作函数参数时遇到的错误
【发布时间】:2019-11-29 15:02:56
【问题描述】:
    #ifndef MENU_H
    #define MENU_H
    #include <cstring>
    #include <string>
    #include <cctype>
    class Menu{
    public:
    Menu();
    void run();
    int selectOptions();
    void rotate90();
    void rotate180();
    void rotate270();
    void flipVert();
    void flipHoriz();
    void convertHigh(int threshold);
    void saveImage(string saveName);
    void loadImage(string loadName);
    void displayMenu();
    private:
    }
    #endif // MENU_H
C:\Users\Wattenphul\Documents\alg-prog design\project04>g++ -std=c++11 -o main.exe main.cpp menu.cpp

In file included from menu.cpp:6:

menu.h:22:20: error: 'string' has not been declared

     void saveImage(string saveName);

                    ^~~~~~

menu.h:22:35: error: expected ',' or '...' before 'saveName'

     void saveImage(string saveName);

                                   ^~~~~~~~

menu.h:23:20: error: 'string' has not been declared

     void loadImage(string loadName);

                    ^~~~~~

menu.h:23:35: error: expected ',' or '...' before 'loadName'

     void loadImage(string loadName);

                                   ^~~~~~~~

menu.h:28:2: error: expected ';' after class definition

 }

这是编译后的代码。它只是头文件,其余代码尚未实现。我不明白为什么字符串不起作用。我也尝试使用分辨率运算符,但这并没有改变结果。

【问题讨论】:

  • C++ 中没有string,只有std::string。要么使用它显式限定,要么添加 using std::string; 以显式将其引入范围。

标签: c++ string compiler-errors g++


【解决方案1】:

它不叫string。它被称为std::string

您可能已经看到了一些名为string 的示例。那是因为作者走捷径,在某处搞错了using namespace std,虽然we don't necessarily recommend doing that

【讨论】:

【解决方案2】:

字符串在namespace std中定义,为了使用你需要在它前面加上std,所以使用std::string而不是string。或者,您可以避免使用 using-directive or using-declaration

为其添加前缀

【讨论】:

  • using namespace std; 添加到头文件中会导致复杂的构建问题。标头在全局范围内不得包含 using namespace
【解决方案3】:

要么使用 std::string 代替字符串,要么在类外部打开命名空间“使用命名空间 std;” 但作为良好的编码习惯,至少在 .h 文件中打开命名空间并不是首选。

【讨论】:

  • using namespace std; 添加到头文件中会引发复杂的构建问题。标头不得在全局范围内包含 using namespaceSee this.
猜你喜欢
  • 2019-09-21
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多