在使用头文件/源文件时访问类变量的麻烦

Trouble with accessing class variables when using header/source files

本文关键字:访问 类变量 麻烦 源文件 文件      更新时间:2023-10-16

我试图利用头文件和它们的源文件,但当我试图访问其中的类时,我遇到了一点麻烦,这是我的头文件的代码:

// 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文件中。