C++ 头文件中未定义的变量
感谢您抽出时间来查看我的问题。我花了很多时间寻找,但找不到解决此问题的方法: 我有一个类Person,其各自的头文件Person.h。cpp类很难理解变量名称、年龄和iq是什么C++ 头文件中未定义的变量,c++,header,C++,Header,感谢您抽出时间来查看我的问题。我花了很多时间寻找,但找不到解决此问题的方法: 我有一个类Person,其各自的头文件Person.h。cpp类很难理解变量名称、年龄和iq是什么 //Person.cpp /* Makes a person. A person has a name, an age, and an IQ level. We will create many of these objects within other classes. */ #include "Person.h"
//Person.cpp
/*
Makes a person.
A person has a name, an age, and an IQ level.
We will create many of these objects within other classes.
*/
#include "Person.h"
Person::Person() //Empty constructor
{
}
Person::Person(string thename, int theage, int theiq)
{
name = thename;
age = theage;
iq = theiq;
}
string getName()
{
return name; //Error: identifier "name" is undefined
}
int getAge()
{
return age; //Error: identifier "age" is undefined
}
int getIq()
{
return iq; //Error: identifier "iq" is undefined
}
void setName(string aName)
{
name = aName; //Error: identifier "name" is undefined
}
void setAge(int aAge)
{
age = aAge; //Error: identifier "age" is undefined
}
void setIq(int aIq)
{
iq = aIq; //Error: identifier "iq" is undefined
}
头文件
//=================================
// include guard
#ifndef __PERSON_H_INCLUDED__
#define __PERSON_H_INCLUDED__
//=================================
// forward declared dependencies
//=================================
// included dependencies
#include <string> //For the name
//=================================
using namespace std;
class Person
{
public:
Person(); //Default constructor
Person(string thename, int theage, int theiq); //Constructor
string getName();
int getAge();
int getIq();
void setName(int aName);
void setAge(int aAge);
void setIq(int aIq);
private:
string name;
int age, iq;
};
#endif //__PERSON_H_
//=================================
//包括警卫
#如果不包括个人__
#定义包含的人员__
//=================================
//前向声明的依赖项
//=================================
//包含的依赖项
#包含//作为名称
//=================================
使用名称空间std;
班主任
{
公众:
Person();//默认构造函数
Person(字符串thename,int theage,int theiq);//构造函数
字符串getName();
int getAge();
int getIq();
无效集合名(内部名称);
无效设置(内部平均值);
无效setIq(国际aIq);
私人:
字符串名;
智力、年龄、智商;
};
#endif//人_
当然我不必在Person.cpp中定义变量,对吗?它已经知道了确切的变量名称、年龄和iq,因为它已经看到了头文件。为什么它不能理解这些变量是什么
如果我做了,或者如果我遗漏了什么,一定要给我说清楚。我只是一个中级C++程序员,所以我可能不懂行话。甚至像范围、继承和定义这样的事情也让我难以理解
谢谢您抽出时间。您需要换衣服
string getName()
到
在.cpp文件中。其他的也一样,编译器需要知道这是类Person的一部分。您的函数
string getName()
{
return name; //Error: identifier "name" is undefined
}
未定义类成员函数。相反,您正在声明和定义一个(完全不同且不相关的)自由函数。因此,
name
在该函数的范围内未定义 在哪一部分出现错误,请执行以下操作:
返回类型Person::函数名(参数)
对于函数的声明部分
例如,对于getAge函数,请执行以下操作:
int Person::getAge() {
return age;
}
出现错误的原因如下:
您忘记将函数定义放在类作用域
Person:
中,就像您正确使用构造函数一样。为什么?这是因为他们是私人的吗?添加CLASSNAME::甚至可以做什么?我是否需要在CPP文件和.H文件中都这样做?我是否还需要定义诸如:Person::int name之类的变量?如果不是,为什么?也许复习你的C++书籍。你在构造函数中得到了正确的结果,只需要用其他方法就可以了
int Person::getAge() {
return age;
}