当我将两个头文件链接在一起时,其中一个无法识别另一个
When I link two header files together, one does not recognize the other
我正在使用c++制作一款包含多个类的桌面游戏。当我在board.h
中包含piece.h
的头文件时,所有的piece成员都被董事会认可。但是,当我同时将board.h
与piece.h
联系起来时,董事会成员没有被识别。下面是我链接它们的方式:
-In piece.h
#ifndef PIECE_H_
#define PIECE_H_
#include <iostream>
#include "board.h"
-In board.h
#ifndef BOARD_H_
#define BOARD_H_
#include<iostream>
#include "piece.h"
我声明了多个棋盘成员和棋盘函数的棋子类型参数,它们工作得很好。然而,在piece中声明一个接受board参数的void函数,如下所示:
void horizontal (Board b);
void vertical (Board b);
void diagonal (Board b);
导致错误提示"Board has not declared"
包含一个文件基本上告诉预处理器"复制该文件的内容在这里"。如果两个头文件相互引用,则有一个无法编译的循环引用。编译器至少要知道一点使用的数据类型。
这可以通过使用前向声明:
Board.h
class Piece; // Forward declaration without defining the type
class Board
{
// Board can makes use of Piece, only as long
// as it does not need to know too much about it.
// References and pointers are ok.
Piece* foo();
void bar(Piece&);
};
Piece.h
#include "Board.h"
class Piece
{
// Actual definition of class.
// At this point Board is fully defined and Piece can make use of it.
Board* foo() { /*...*/ }
void bar(Board& x) { /*...*/ }
// Not only references are possible:
Board baz(const Board x) { /*...*/ }
};
Board.cpp
#include "Board.h"
#include "Piece.h"
// Implementation of Board's functions can go after Piece's definition:
Piece* Board::foo() { /*...*/ }
void Board::bar(Piece& x) { /*...*/ }
这个包含方案有两个备选视图。当包含piece.h时,所有的board.h都包含在piece.h主体之前。
当包含board.h时,所有的piece.h都包含在board
之前让类一起工作
1)你需要预先声明至少一个类。2)要使用类,编译器要么需要使用引用(或指针),要么需要知道类的大小。
class Board;
那么可以使用
void horizontal ( Board & b );
不知道其大小
试着把这个放到"piece.h"的顶部
class Board;
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口