2016-03-05 175 views
-1

我试图将我的C++代码分离为一个头文件和一个cpp文件,但是解释器显示了一些错误。C++ .h和.cpp文件分开

这里是我的代码:

Password.h:

#ifndef PASSWORD_H 
#define PASSWORD_H 

class Password { 
private: 
    string aliasName_; 
    int hashOfPassword_; 
public: 
    void setAliasName(string aliasName); 
    void setHashOfPassword(int hashOfPassword); 
    string getAliasName() { return aliasName_; } 
    int getHashOfPassword() { return hashOfPassword_; } 
}; 

#endif 

Password.cpp:

#include <string> 
#include "Password.h" 

using std::string; 

void Password::setAliasName(string aliasName) { 
    aliasName_ = aliasName; 
} 
void Password::setHashOfPassword(int hashOfPassword) { 
    hashOfPassword_ = hashOfPassword; 
} 

错误:

Error C2065 'aliasName_': undeclared identifier X\password.cpp 7 
Error C2511 'void Password::setAliasName(std::string)': overloaded member function not found in 'Password' X\password.cpp 6 
Error C3646 'aliasName_': unknown override specifier X\password.h 6 
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int X\password.h 6 
Error C2061 syntax error: identifier 'string' X\password.h 9 
Error C3646 'getAliasName': unknown override specifier X\password.h 11 
Error C2059 syntax error: '(' X\password.h 11 
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body X\password.h 11 

任何人有任何想法?

+6

您需要在标题中添加'using std :: string;'或使用'std :: string'。 –

+2

你听说过'const'吗? –

+0

谢谢Mats Petersson,工作正常! :-) – Gabor

回答

3

你需要你的类的声明之前移动using std::string

#ifndef PASSWORD_H 
#define PASSWORD_H 

#include <string> 

using std::string; 

class Password { 
… 

,并从您的.cpp文件中删除。

此外,您可能需要使用#pragma once而不是传统的#ifndef/#define/#endif,最后您可能希望在需要时使参数和方法为常量。

+0

谢谢你Zmo快速回答:) – Gabor

+0

没问题,如果它对你有帮助,请不要犹豫+1并接受它;-) – zmo

+0

我认为在头文件中使用'using'会很糟糕实践。但是,如果它不是图书馆,我认为它并不重要。另一件事:我不知道GCC支持'#pragma once'。上次我搜索它时,我只看到它是VC的扩展。但[这个线程](http://stackoverflow.com/q/1143936/4967497)表示它受到所有常见编译器的支持。 O.o – JojOatXGME

1

你需要移动

#include <string> 
using std::string; 

里面Password.h,那么你可以从Password.cpp删除这两条线。

0

只需将std::添加到头文件中的每个string并记住,您不应该在那里使用usingusing namespace!您还应该将所有标题包含在您使用它们的文件中。