使头文件与.cpp文件一起工作
Getting header files to work with .cpp files
我正试图学习如何使用。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
行)。
相关文章:
- 将 getline() 与文件一起使用
- 与clang++一起使用的VS代码在构建良好的C++文件中显示错误
- 我应该如何获取配置文件的绝对路径与 Windows .exe一起发布?
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 无法使包含.hpp文件与其中的2个文件一起使用
- 您是否必须随项目一起交付原型文件?
- 将boost::filtering_streambuf与newline_filter一起使用时为空文件
- 有没有办法将 getline() 与外部文本文件一起使用,然后重新获得 cin 的控制权以从控制台获取输入?
- 如何制作一个与.txt文件一起使用的C 程序而不显示
- 将qresource qfile与文件一起使用
- 如何将boost::iostreams::mapped_file_source与gzip输入文件一起使用
- 在 C++ 中将 IFstream 与字符串而不是文件一起使用
- argv 和 argc 与输入/输出文件一起使用
- Visual Studio 2012将项目模板与文件一起导出
- 将HeaderDoc与.hpp文件而不是.h文件一起使用
- 使头文件与.cpp文件一起工作
- 试图与可执行文件一起使用gdb时出现问题
- 如何将fltk文件与其他文件一起编译
- 在带有Rcpp的R包中,将头(.h)文件与cpp文件一起使用
- rand()函数不能与文件I/O一起工作