【问题标题】:'string' does not name a type - c++ error [closed]'string'没有命名类型 - C++错误[关闭]
【发布时间】:2016-04-14 17:03:44
【问题描述】:

我是 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::string moduleName;
  • 我没听懂。我应该修改哪个文件?你能逐步解释一下吗?
  • 我和许多其他人强烈建议不要尝试通过在标题中添加using namespace std; 来解决此问题。它并不总是会导致痛苦,但它会导致比你想忍受的更多的悲伤。更多信息:stackoverflow.com/questions/1452721/…
  • SergeyA 的观点是没有string 这样的东西。但是有std::string。您正在使用 wring 名称。
  • @downvoters 找一个好的骗子或者闭嘴。

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


【解决方案1】:

您必须在头文件中明确使用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:: 范围。

【讨论】:

  • 更好的是,.cpp 中根本没有using。 std::string 就好了。
  • @SergeyA 如果它没有歧义,那么就像提到的那样,完全可以。
  • 在这种情况下“严重”是什么意思? 总体?
  • 它现在给了我一个新错误。错误:从 'std::__cxx11::string {aka std ::__cxx11::basic_string}'
  • @SergeyA 我的意思是,在很多情况下都可以。
猜你喜欢
  • 2019-02-07
  • 2015-12-01
  • 1970-01-01
  • 2017-12-08
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
相关资源
最近更新 更多