1

我是初学者。我不知道为什么我不能使用字符串。它说string does not have a type

主文件

    #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 xstring x

4

1 回答 1

7

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

#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 ...并接受在命名空间前附加的额外类型。

于 2012-07-09T13:30:22.110 回答