C++ C++;将类的引用传递给另一个类
我一直在试图通过我的图形管理课程,以我的机器人和房间类 但是当试图通过引用传递类时,我得到了3个关于通过引用传递的错误 以下是我所指的错误: C2143语法错误:缺少“;”在“*”之前 C4430缺少类型说明符-假定为int。注意:C++不支持默认INT/P> C2238“;”之前的意外标记 我试图改变我传递类的方式,但运气不好,我突出显示了导致错误的区域以及我试图用来解决问题的代码 非常感谢您对我如何解决这些错误的任何建议 我没有包括完整的.cpp文件,因为它们相当大,但我将包括一个指向带有完整脚本的粘贴库的链接 图形经理C++ C++;将类的引用传递给另一个类,c++,visual-studio,class,pointers,reference,C++,Visual Studio,Class,Pointers,Reference,我一直在试图通过我的图形管理课程,以我的机器人和房间类 但是当试图通过引用传递类时,我得到了3个关于通过引用传递的错误 以下是我所指的错误: C2143语法错误:缺少“;”在“*”之前 C4430缺少类型说明符-假定为int。注意:C++不支持默认INT/P> C2238“;”之前的意外标记 我试图改变我传递类的方式,但运气不好,我突出显示了导致错误的区域以及我试图用来解决问题的代码 非常感谢您对我如何解决这些错误的任何建议 我没有包括完整的.cpp文件,因为它们相当大,但我将包括一个指向带有完
#pragma once
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Room.h"
#include "Robot.h"
class GraphicsManager
{
public:
Room* room; //This does not Flag Up Errors
Robot* robot; //This does not Flag Up Errors
h房间
#pragma once
#include <SFML/Graphics.hpp>
#include <SFML/System/String.hpp>
#include "GraphicsManager.h" //
//#include "Robot.h" //what i orginally had
//class GraphicsManager; //i decided not to do it this way
class Robot; //What i changed it to
class Room
{
public:
//Reference to other classes
Room* room; //This doesnt throw errors
Robot* robot; //This doesnt throw errors
//Refference to graphics manager
GraphicsManager *gm; //This throws the three errors mentioned
};
这是一个经典的问题
GraphicsManager.h
包括Room.h
和Robot.h
,其中每一个都包括GraphicsManager.h
。现在,例如,在编译GraphicsManager.cpp
时,包括GraphicsManager.h
。但是在进入GraphicsManager
类定义之前,首先要包括Room.h
。从那里,您可以直接再次包含graphicsmanager.h
,但由于其中有一个#pragma
,编译器将跳过该包含。当编译器到达GraphicsManager*gm在Room.h
中,is从未见过名为GraphicsManager
的类型的声明。VisualC++给你的错误消息,那么
C4430缺少类型说明符-假定为int。注意:C++不支持默认INT/P>
可以说有点不直观。在遇到标识符时,标识符只能表示声明的开始。由于GraphicsManager
不是已知类型,编译器假定标识符必须是应该声明的实体的名称,而您只是忘记了指定类型。这就是为什么您会看到错误消息。在过去,C允许您在声明中省略类型说明符,这意味着使用int
作为默认值。因此,您将看到这个错误是由于试图编译古老的、非标准的C代码造成的。这就是为什么错误消息包含不允许的明确注释
您已经为Robot.h
中的Room
和Robot.h
添加了转发声明。对于GraphicsManager
…您也必须这样做,它们看起来都像是微不足道的打字错误。可能只包括错误所在的行和两侧的3或4行(通常这些类型的错误可能来自报告前几行的错误)
#include "Robot.h"
Robot::Robot()
{
gm = new GraphicsManager(room, robot); //This tells me gm is
//not declared
this->room = room; //This does not flag up errors
this->robot = robot; //This does not flag up errors
//Room &room = *rm; // attempted to use this but decided not
//to
}
#pragma once
#include <SFML/Graphics.hpp>
#include <SFML/System/String.hpp>
#include "GraphicsManager.h" //
//#include "Robot.h" //what i orginally had
//class GraphicsManager; //i decided not to do it this way
class Robot; //What i changed it to
class Room
{
public:
//Reference to other classes
Room* room; //This doesnt throw errors
Robot* robot; //This doesnt throw errors
//Refference to graphics manager
GraphicsManager *gm; //This throws the three errors mentioned
};
#include "Room.h"
Room::Room()
{
gm = new GraphicsManager(room, robot);
this->room = room;
this->robot = robot;