我正在尝试使用头文件及其源文件,但是当我尝试访问其中的类时,我遇到了一些麻烦,这是我的头文件的代码:
// 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 data\n";
cout << "====================\n";
getValues ( p1 );
return 0;
}
我得到的编译器(即MS Visual C ++)错误是:
'p1' uses undefined class
和
setValues cannot convert an int
getValues cannot convert an int
或类似的东西。
有人对我做错了什么有任何想法吗?或者是否有某种方法来访问类中的变量?
答案 0 :(得分:1)
编译Person
时,编译器必须可以使用类main
的完整声明。
您应该将类定义放在头文件中(并将其包含在主文件中)。您可以将成员函数的实现保留在单独的.cpp
文件中。