使用字符串时出现问题

Trouble using strings

本文关键字:问题 字符串      更新时间:2023-10-16

我是个初学者。我不知道为什么我不能使用字符串。上面写着string does not have a type

main.cpp

    #include <iostream>
    #include <string>
    #include "Pancake.h"
using namespace std;
int main() {
    Pancake good;
    good.setName("David");
    cout << good.name << endl;
}

煎饼.h

#ifndef PANCAKE_H
#define PANCAKE_H
#include <string>
class Pancake {
    public:
        void setName( string x );
        string name;
    protected:
    private:
};
#endif // PANCAKE_H

煎饼.cpp

#include <iostream>
#include "Pancake.h"
#include <string>
using namespace std;
void Pancake::setName( string x ) {
    name = x;
}

只有当我使用字符串时才会发生这种情况。当我在string x的所有实例中使用整数并用int x替换string x时,它就起作用了。但为什么呢?

您只需在头文件中省略名称空间:

#ifndef PANCAKE_H
#define PANCAKE_H
#include <string>
class Pancake {
    public:
        void setName( std::string x );
        std::string name;
    protected:
    private:
};
#endif // PANCAKE_H

最好避免使用using namespace ...,而是接受在名称空间前面加上前缀的额外类型。