c++ - 解决 C++ 头文件中的循环引用

标签 c++

<分区>

我遇到循环包含引用错误,我希望在 CardFactory 中使用 Deck 类型的对象,并在 Deck 中使用 CardFactory 类型的对象。关于如何解决此问题的任何提示?

//CardFactory.h
#ifndef CARDFACTORY_H
#define CARDFACTORY_H

#include "Deck.h"

#include <string>

using std::string;

class CardFactory {

public:
    Deck getDeck();
    static CardFactory* getFactory() {
        static CardFactory singleton;
        return &singleton;
    }

};

#endif

//Deck.h
#ifndef DECK_H
#define DECK_H

#include <vector>
#include <iostream>
#include "CardFactory.h"
using std::ostream;

class Deck : public std::vector<Card*> {
    friend ostream& operator<<(ostream& os, const Deck& dt);
    Card* draw();
    Deck(CardFactory* cf);
};

#endif

最佳答案

前向引用(或前向声明)。

Deck.h 中,您不需要#include "CardFactory.h",只需声明类即可。

class CardFactory;

这应该有效,因为在 Deck 类中,您只使用指向类 CardFactory 的指针

关于c++ - 解决 C++ 头文件中的循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40924515/

相关文章:

c++ - 结构化绑定(bind)初始化程序表单 { assignment-expression } 在 clang 上的数组类型失败

c++ - C++ 中的引用语义

c++ - 从 SDL_Surface 到 QPixmap 的高效转换

c++ - c++中多态和函数重载的区别

c++ - 如何截断 XMM 寄存器中的浮点值

c++ - 使用 strcat 附加字符数组不起作用

c++ - 模板的模板的参数类型推导规则是什么?

c++ - 基类和派生类中的模板成员之间的重载解析

c++ - 如何让 Qt 5.8 在 Windows 上使用 OpenSSL

c++ - Boost C++ 库中 Log 函数的问题