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

C++。h和.cpp文件是分开的 我试图把我的C++代码分割成一个头文件和一个CPP文件,但是解释器显示了一些错误。,c++,C++,这是我的密码: 密码。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()

这是我的密码:

密码。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
#include <string>
#include "Password.h"

using std::string;

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

#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
#include <string>
#include "Password.h"

using std::string;

void Password::setAliasName(string aliasName) {
    aliasName_ = aliasName;
}
void Password::setHashOfPassword(int hashOfPassword) {
    hashOfPassword_ = hashOfPassword;
}
有人有什么想法吗?

你得走了

#include <string>
using std::string;
#包括
使用std::string;

要进入
Password.h
,您可以从
Password.cpp

中删除这两行。在声明类之前,您需要使用std::string移动

#ifndef PASSWORD_H
#define PASSWORD_H

#include <string>

using std::string;

class Password {
…
\ifndef密码\u H
#定义密码
#包括
使用std::string;
类密码{
…
并将其从.cpp文件中删除


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

只需将
std:
添加到头文件中的每个
字符串
,请记住,您永远不要使用
我们你需要在你的头中添加
使用std::string;
或者使用
std::string
。你听说过
const
吗?谢谢Mats Peterson,工作很好!-)谢谢你的快速回答:)没问题,如果它对你有帮助的话,请回答不要犹豫+1并接受它;-)我认为在头文件中使用
是不好的做法。但如果它不是一个库,我认为这并不重要。另一件事:我不知道GCC支持
#pragma once
。上次搜索它时,我只看到它是VC的扩展。但我说所有常见的编译器都支持t。O.oit相对较新,我相信它是随着C++11的支持而添加的,所以在GCC的最后2或3个版本中。关于
使用
,您需要访问该类型,因此您需要在标题中包含
。尽管在hea中使用
确实是一种不好的做法der,因为如果你的库的用户(考虑到它变成了一个库)可能会在他的
名称空间中包含你的头,并用
std
中的符号污染名称空间。所以最好执行
#include
,并在头文件中调用原型中
std::string
的完整“路径”。