'string'没有命名类型--c ++错误

Ajm*_*eel -1 c++ compiler-errors c++11

我是C++的新手.我最近制作了一个在单独文件中使用类的小程序.我还想使用setter和getter(set&get)函数为变量赋值.当我运行程序时,编译器给我一个奇怪的错误.它说'string'没有命名类型.这是代码:

MyClass.h

#ifndef MYCLASS_H   // #ifndef means if not defined
#define MYCLASS_H   // then define it
#include <string>

class MyClass
{

public:

   // this is the constructor function prototype
   MyClass(); 

    void setModuleName(string &);
    string getModuleName();


private:
    string moduleName;

};

#endif
Run Code Online (Sandbox Code Playgroud)

MyClass.cpp文件

#include "MyClass.h"
#include <iostream>
#include <string>

using namespace std;

MyClass::MyClass()  
{
    cout << "This line will print automatically because it is a constructor." << endl;
}

void MyClass::setModuleName(string &name) {
moduleName= name; 
}

string MyClass::getModuleName() {
return moduleName;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp文件

#include "MyClass.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    MyClass obj; // obj is the object of the class MyClass

    obj.setModuleName("Module Name is C++");
    cout << obj.getModuleName();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

πάν*_*ῥεῖ 5

您必须std::在头文件中显式使用命名空间作用域:

class MyClass {    
public:

   // this is the constructor function prototype
   MyClass(); 

    void setModuleName(std::string &); // << Should be a const reference parameter
                    // ^^^^^
    std::string getModuleName();
 // ^^^^^    

private:
    std::string moduleName;
 // ^^^^^    
};
Run Code Online (Sandbox Code Playgroud)

在你的.cpp文件中你有

using namespace std;
Run Code Online (Sandbox Code Playgroud)

这是非常好的,但应该更好

using std::string;
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,还std::明确使用标题中的范围.