2016-04-14 39 views
-1

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

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

'std :: string moduleName;' – SergeyA

+0

我没有得到它。我应该修改哪个文件?你可以一步一步解释。 –

+0

我和很多其他人强烈建议不要试图通过在标题中添加'using namespace std ;'来解决此问题。它并不总是会导致痛苦,但它会导致比您想要忍受的更多的悲伤。更多在这里:http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice – user4581301

回答

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::范围明确像标题。

+0

更好的是,在.cpp中根本没有“使用”。 'std :: string'就好了。 – SergeyA

+0

@SergeyA如果它明确无误,就像上面提到的那样_grossly OK_。 –

+0

在这种情况下,“严重”意味着什么? *总体*? – SergeyA