"字符串"未命名类型 - C++ 错误

'string' does not name a type - c++ error

本文关键字:C++ 错误 类型 字符串 未命名      更新时间:2023-10-16

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

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

您必须在头文件中显式使用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::作用域。