代码之家  ›  专栏  ›  技术社区  ›  bobber205

无法使用STL的字符串类

  •  1
  • bobber205  · 技术社区  · 15 年前

    以前遇到过这个问题,但忘记了我是如何解决的。

    我想使用STL字符串类,但编译器抱怨找不到它。 这是完整的.h文件。

    #ifndef MODEL_H
    #define MODEL_H
    
    #include "../shared/gltools.h"  // OpenGL toolkit
    #include <math.h>
    #include <stdio.h>
    #include <string>
    #include <iostream>
    
    #include "Types.h"
    
    class Model
    {
    
    public:
    
        obj_type_ptr p_object;
        char Load3DS (char *p_filename);
        int LoadBitmap(char *filename);
    
        int num_texture;
        string fun("alex");
    
        Model(char* modelName, char* textureFileName);
    };
    
    #endif
    
    4 回复  |  直到 15 年前
        1
  •  11
  •   Anon.    15 年前

    你想用 std::string 是吗?

    你只是在使用 string . 如果你有一个 using namespace ... 声明,但在头文件中不是一个好主意。

        2
  •  3
  •   Potatoswatter    15 年前

    STL中的每个标识符都位于 std 命名空间。直到你这样做 using namespace std; , using std::string; typedef std::string xxx; ,必须叫它 std::string .

    任何种类的 using 正如其他人提到的,在头中声明,尤其是在自己的命名空间之外声明是一个坏主意。

    所以,进口 STD::字符串 进入课堂:

    class Model
    {
        typedef std::string string;
    
        public:
    
        3
  •  1
  •   Chris H    15 年前

    噢,标准::字符串。不要在头文件btw中使用using命名空间。

        4
  •  1
  •   AshleysBrain    15 年前

    除了其他答案提到的名称空间问题之外,不能在变量声明处将其构造为类成员。假设你把它改成

    class Model {
        // ...
        std::string fun("alex");
    };
    

    这在类中仍然是非法的,不能在声明中分配值,必须将其保留:

    class Model {
        // ...
        std::string fun;
    };
    

    如果要在创建时将其命名为“alex”,请在构造函数中对其进行初始化:

    Model::Model(...)
        : fun("alex")  // initialiser
    {
        // ...
    }