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

时间:2016-04-14 17:03:45

标签: c++ c++11 compiler-errors

我是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

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;
}

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;
}

1 个答案:

答案 0 :(得分: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;
 // ^^^^^    
};

在您的.cpp文件中

using namespace std;

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

using std::string;

甚至更好,还明确使用std::范围,如标题中所示。