使用头文件/源文件时访问类变量时出现问题

问题描述 投票:0回答:1

我正在尝试利用头文件及其源文件,但是当我尝试访问其中的类时,我遇到了一些麻烦,这是我的头文件的代码:

// 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

或者类似的东西。

有人对我做错了什么有什么想法吗?或者有某种方法可以访问类中的变量吗?

c++ class variables
1个回答
1
投票

编译器编译您的

Person
时,必须可以使用类
main
的完整声明。

您应该将类定义放在头文件中(并将其包含在主文件中)。不过,您可以将成员函数的实现保留在单独的

.cpp
文件中。

© www.soinside.com 2019 - 2024. All rights reserved.