在使用头文件/源文件时访问类变量的麻烦
Trouble with accessing class variables when using header/source files
我试图利用头文件和它们的源文件,但当我试图访问其中的类时,我遇到了一点麻烦,这是我的头文件的代码:
// person.h
namespace PersonFuncs
{
class Person;
void getValues ( Person& );
void setValues ( Person& );
}
和我的头文件源文件:
// person.cpp
#include <iostream>
#include <string>
#include "person.h"
using namespace std;
namespace PersonFuncs
{
class Person
{
private:
string name; // Declaring string variable to hold person's name
int height; // Declaring integer variable to hold person's height
public:
string getName() const; // Reads from 'name' member variable
void setName ( string ); // Writes to the 'name' member variable
int getHeight() const; // Reads from the 'height' member variable
void setHeight ( int ); // Writes to the 'height' member variable
};
string Person::getName() const
{
return name;
}
void Person::setName ( string s )
{
if ( s.length() == 0 ) // If user does not input the name then assign with statement
name = "No name assigned";
else // Otherwise assign with user input
name = s;
}
int Person::getHeight() const
{
return height;
}
void Person::setHeight ( int h )
{
if ( h < 0 ) // If user does not input anything then assign with 0 (NULL)
height = 0;
else // Otherwise assign with user input
height = h;
}
void getValues ( Person& pers )
{
string str; // Declaring variable to hold person's name
int h; // Declaring variable to hold person's height
cout << "Enter person's name: ";
getline ( cin, str );
pers.setName ( str ); // Passing person's name to it's holding member
cout << "Enter height in inches: ";
cin >> h;
cin.ignore();
pers.setHeight ( h ); // Passing person's name to it's holding member
}
void setValues ( Person& pers )
{
cout << "The person's name is " << pers.getName() << endl;
cout << "The person's height is " << pers.getHeight() << endl;
}
}
两者都编译没有错误!但是在下面这段代码中,你可能会看到我试图利用'Person'类:
// Person_Database.cpp
#include <iostream>
#include "person.h"
using namespace std;
using namespace PersonFuncs
int main()
{
Person p1; // I get an error with this
setValues ( p1 );
cout << "Outputting user datan";
cout << "====================n";
getValues ( p1 );
return 0;
}
编译器(这是MS Visual c++)我得到的错误是:
'p1' uses undefined class
和
setValues cannot convert an int
getValues cannot convert an int
之类的
谁知道我做错了什么?或者是否有某种方法可以访问类中的变量?当编译器编译main
时,必须提供Person
类的完整声明。
您应该将类定义放在头文件中(并将其包含在主文件中)。您可以将成员函数的实现留在单独的.cpp
文件中。
相关文章:
- 访问类成员而不复制此变量或互斥变量
- 分段 访问私有类变量时出错
- 如何访问基类向量中的子类变量?(对于实体组件系统)
- 访问类对象以与全局变量进行比较
- 如何在构造函数中访问类变量以分配它们,而无需在C++中使用此指针
- 访问类成员的成员变量时 cpp 程序挂起
- 类变量无法从类方法访问
- 从静态成员函数访问私有非静态类变量 - C++
- 如何使用对象数组访问类中的变量?
- 无法使用子类变量访问超类公共成员
- 为什么我无法使用继承类访问私有变量?
- 为什么可以从类中的对象访问类的私有变量
- 创建函数来访问类变量是一种好的做法吗
- 从std::thread访问类变量
- 如何访问类变量?公共方法/getters与继承.优点和缺点是什么
- 在使用头文件/源文件时访问类变量的麻烦
- 如何从外部"C"函数访问类变量?
- 无法访问类变量
- 访问类变量时出现问题
- 友元函数无法访问类变量