使头文件与.cpp文件一起工作

Getting header files to work with .cpp files

本文关键字:文件 一起 工作 cpp      更新时间:2023-10-16

我正试图学习如何使用。h文件与我的。cpp文件和任何时候我运行我的代码,我得到错误与几乎每一个变量,我有。

这是我的。h文件:

class Person
{
public:
    Person(
        string firstNames, 
        string lastNames, 
        string socialSecurityNumber, 
        string gender)
        : firstNames(firstNames), 
        lastNames(lastNames), 
        socialSecurityNumber(socialSecurityNumber)
        {}
    string getFirstNames() const;
    void setFirstNames(string aFirstNames);
    string getLastNames() const;
    void setLastNames(string aLastNames);
...
private:
    string firstNames;
    string lastNames;
    string socialSecurityNumber;
    string gender;
};

我的。cpp文件:

#include "stdafx.h"
#include <ctime>
#include <string>
#include "Person.h"
using namespace std;
string Person::getFirstNames() const
{
    return firstNames;
}
void Person::setFirstNames(string aFirstNames)
{
    firstNames = aFirstNames;
}
string Person::getLastNames() const
{
    return lastNames;
}

您可以在构造函数中看到的其他变量的函数继续。每当我尝试构建这个时,它就会给我错误,例如:

'getFirstNames'不是'Person'的成员
非成员函数不允许使用'getFirstNames':修饰符
'firstNames'未声明的标识符

我刚刚开始学习c++和使用头文件,但来自Java背景,不知道为什么这些错误会出现。从我在网上做的研究来看,这应该是有效的,但显然没有。

Person的定义在using namespace std之前,所以在报头中使用string是无效的。

头文件没有必须首先包含的依赖关系是很好的做法,为了确保这一点,我总是在库或系统头文件之前包含我的本地头文件:

#include "Person.h"
#include <ctime>
#include <string>

在你的标题中,确保它包含了它需要的东西:

#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED
#include <string>
class Person
{
public:
    Person(
          std::string firstNames, 
          std::string lastNames, 
          std::string socialSecurityNumber, 
          std::string gender)
      : firstNames(firstNames), 
        lastNames(lastNames), 
        socialSecurityNumber(socialSecurityNumber)
      {}
   ...
};
#endif

不要在头文件中尝试using namespace -这会将符号带入全局命名空间,并且被认为是对头文件用户的粗鲁。

(顺便说一句,在i18n问题上-要小心假设每个人都有"名"answers"姓",以及其中哪个(如果有的话)是"姓"…)

经OP确认(见问题注释):

.h文件缺少以下行:

using namespace std;

标题使用string,它是std命名空间的一部分。

或者,将所有string实例替换为std::string(因此,不需要using namespace std行)。