C ++将类的引用传递给另一个类

时间:2018-11-28 21:24:48

标签: c++ visual-studio class pointers reference

我一直试图将我的Graphics Manager类传递给我的Robot和Room类。

但是当尝试通过引用传递类时,关于通过引用传递,我会遇到3个错误。

这些是我指的错误: C2143语法错误:缺少';'在“ *”之前

C4430缺少类型说明符-假定为int。注意:C ++不支持default-int

C2238';'之前的意外令牌

我试图更改传递类的方式,但是没有运气,我重点介绍了导致错误的区域以及我试图用来解决问题的代码。 / p>

任何有关如何解决这些错误的建议都将受到高度赞赏。

我没有包含完整的.cpp文件,因为它们很大,但是我将包含具有完整脚本的pasteBin的链接。

GrapicsManager.h

#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 

Robot.h

#pragma once
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/System/String.hpp>
#include "GraphicsManager.h"
//#include "Room.h" //This what i had
class Room; //This is what i changed
//class GraphicsManager; //Wasnt sure if i should use it this 
//way

class Robot
{
public:

//Graphics Variables
Room* room;     //This works after the change
Robot* robot;   //This works after the change

GraphicsManager *gm;    //This throughs up the error

//This Is what i attemped to use with no effect
//GraphicsManager* gm = new GraphicsManager(room, robot);

Robot.cpp https://pastebin.com/Xd1A3Vii

#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

}

Room.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
};

Room.cpp https://pastebin.com/6R6vnVfy

#include "Room.h"



Room::Room()
{

gm = new GraphicsManager(room, robot);
this->room = room;
this->robot = robot;

1 个答案:

答案 0 :(得分:0)

这是经典的包含头问题。 GrapicsManager.h包括Room.hRobot.h,它们分别又包含GrapicsManager.h。现在,例如,在编译GraphicsManager.cpp时,您包括了GrapicsManager.h。但是在获得GraphicsManager类定义之前,首先要包含Room.h。从那里开始,您可以直接再次包含GrapicsManager.h,但是由于那里有一个#pragma once,因此编译器将直接跳过该包含。到编译器到达GraphicsManager *gm;中的Room.h成员声明时,再也没有见过名为GraphicsManager的类型的声明。然后,Visual C ++会给您错误消息

  

C4430缺少类型说明符-假定为int。注意:C ++不支持default-int

可能有点不直观。在遇到标识符GraphicsManager时,标识符只能表示声明的开始。由于GraphicsManager不是已知类型,因此编译器会假定标识符必须是应该声明的实体的名称,而您只是忘记了指定类型。这就是为什么您收到看到的错误消息的原因。过去的C用来允许您在声明中省略类型说明符,这仅意味着使用int作为默认值。因此,您会由于尝试编译古老的非标准C代码而看到此错误。这就是为什么错误消息包含不允许的明确注释的原因...

您已经在Room中为Robot.hRobot中的Room.h添加了前向声明。您必须对GraphicsManager做同样的事情……