Qt中的C ++前向声明

时间:2018-06-12 05:44:47

标签: c++ qt qt5 forward-declaration

我有三个相互依赖的课程:

class Channel
{
public:

enum ChannelType {
    DIMMER, RED, GREEN, BLUE, STROBE
};

Channel(ChannelType type);
const ChannelType type;

void x(Fixture fixture);
};

class Fixture
{
    public:
    Fixture(int channel, FixturePattern pattern);

    Channel getChannel(const Channel::ChannelType);

    private:
        const int channel;
        FixturePattern pattern;
};

class FixturePattern
{

public:
    FixturePattern(QList<Channel> channels);
    Channel getChannel(Channel::ChannelType type);

private:
    QList<Channel> channels;
};

这些类位于单独的头文件中。我尝试将它们与#include连接起来,但我总是以不完整的类型或XY was not declared in this scope错误结束。有人可以解释一下我做错了什么吗? 我没有添加#include,因为我昨天完全搞砸了。最近我找到了question这个主题,但我不想把它放在同一个文件中。有可能吗?

1 个答案:

答案 0 :(得分:0)

如果没有详细介绍,您应该为您的课程使用前向声明。您需要修改代码才能执行此操作。代码看起来应该是这样的。我没有测试它但它应该可以工作。

class Fixture; // the forward deceleration 
class Channel
{
public:

enum ChannelType {
    DIMMER, RED, GREEN, BLUE, STROBE
};

Channel(ChannelType type);
const ChannelType type;

void x(const Fixture &fixture); // or void x(Fixture *fixture);
};

#include "FixturePattern.h" 
class Fixture
{
    public:
    Fixture(int channel,const FixturePattern &pattern);

    Channel getChannel(const Channel::ChannelType); 

    private:
        const int channel;
        FixturePattern pattern;
};

#include "Channel.h"
class FixturePattern
{

public:
    FixturePattern(QList<Channel> channels);
    Channel getChannel(Channel::ChannelType type);

private:
    QList<Channel> channels;
};