简体   繁体   English

类指针作为另一个对象的数据成员

[英]Class Pointer as a Data Member of Another Object

just getting an odd error and I'm not entirely sure as to why. 只是得到一个奇怪的错误,我不完全知道为什么。

I have 4 files (two headers and two implementations). 我有4个文件(两个标头和两个实现)。 The issue is inside the headers: 问题在标题内:

The main file ONLY includes the Station.h, which is why Stations.h is included inside it. 主文件仅包含Station.h,这就是为什么其中包含Stations.h的原因。

Station.h 站h

#ifndef STATION_H
#define STATION_H
#include "Stations.h"

#include <string>

enum PassType{student, adult};

class Station{

        std::string station_name;
        unsigned int student_passes;
        unsigned int adult_passes;

    public:
        Station();
        void set(const std::string&, unsigned, unsigned);
        void update(PassType, int);
        unsigned inStock(PassType) const;
        const std::string& getName() const;

};


#endif

Stations.h Stations.h

#ifndef STATIONS_H
#define STATIONS_H
#include "Station.h"

namespace w2{

    class Stations{

    Station *station;

    public:
        Stations(char *);
        void update() const;
        void restock() const;
        void report() const;
        ~Stations();

    };

}

#endif

It doesn't know what Station is. 它不知道什么是车站。 I'm getting the following error: 我收到以下错误:

./Stations.h:9:2: error: unknown type name 'Station'; did you mean 'Stations'?
        Station *station;

What exactly am I missing here? 我在这里到底想念什么?

Don't forget to put a semicolon after you declare the Stations class: 声明Stations类后,不要忘记添加分号:

class Stations {
     Station *station;
};

U need to do the forward declaration. 您需要做前向声明。 Remove the #include "Stations.h" from the Station.h 从Station.h中删除#include“ Stations.h”

#ifndef STATIONS_H
#define STATIONS_H
#include "Station.h"

namespace w2{
    class Station;
    class Stations{

    Station *station;

    public:
        Stations(char *);
        void update() const;
        void restock() const;
        void report() const;
        ~Stations();

    };

}

#endif

You are #include ing Stations.h in Station.h. 您正在#include stationing.h中包含Stations.h。 As a result, the compiler sees class Stations before class Station . 结果,编译器将在class Station class Stations之前看到class Station In this case, it doesn't appear that Station requires Stations , so you can simply remove the include. 在这种情况下,似乎Station不需要Stations ,因此您只需删除包含。

If Station did need to know about Stations , then you'd have to use a forward declaration in one of the headers or the other (and be careful not to use the forward-declared class in a way that required the full definition). 如果Station 确实需要了解Stations ,那么您必须在头文件或其他头文件中使用前向声明(请注意不要以要求完整定义的方式使用前向声明的类)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM