【问题标题】:Passing objects as parameters by another object visual c++将对象作为参数传递给另一个对象visual c ++
【发布时间】:2014-10-31 23:53:18
【问题描述】:

我试图在 C++ 中通过引用传递一个对象。我收到这些错误:

错误 1 ​​错误 C2061:语法错误:标识符 'Common' graphics.h 6 1 SDLGameDev

错误 2 错误 C2511: 'void Graphics::CreateWindow(Common &)' : 在 'Graphics' 4 1 SDLGameDev 中找不到重载的成员函数

我找到了关于这个领域的答案,但没有找到任何关于如何做到这一点的答案:

object1.someFunction(object2);

这是我的代码:

//Common.h

#ifndef COMMON_H
#define COMMON_H
#include "SDL.h"
#include "iostream"

class Common{
public:
    void Init();
    bool GetGameRunState(){ return GameRunState; }
    void SetGameRunState(bool x){ GameRunState = x; }
private:
    bool GameRunState;
};

#endif 

//Commmon.cpp

#include "Common.h"

void Common::Init()
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        SetGameRunState(true);
    }
    else
    {
        SetGameRunState(false);
    }
}

//图形.h

#ifndef GRAPHICS_H
#define GRAPHICS_H

class Graphics{
public:
    void CreateWindow(Common & co);
};

#endif

//图形.cpp

#include "Graphics.h"
#include "Common.h"
void Graphics::CreateWindow(Common & co)
{
    if (co.GetGameRunState() == true)
    {
        std::cout << "TEST for CreateWindow()\n";
    }
}

//main.cpp

#include "Common.h"
#include "Graphics.h"

Common co;
Graphics go;

int main(int argc, char * args[])
{
    co.Init();
    go.CreateWindow(co);
    while (co.GetGameRunState() == true)
    {
        std::cout << "Game is running\n";
        SDL_Delay(2000);
        break;
    }

    return 0;
}

【问题讨论】:

    标签: object visual-c++ parameters sdl pass-by-reference


    【解决方案1】:

    您没有在文件 Graphics.h 中包含 Common.h,因此它不知道该类。

    #ifndef GRAPHICS_H
    #define GRAPHICS_H
    
    #include "Common.h"  // You need this line
    
    class Graphics {
    public:
        void CreateWindow(Common & co);
    };
    
    #endif
    

    【讨论】:

    • 哇,太痛苦了。非常感谢 Zammalad!
    【解决方案2】:

    我建议使用单例并将 sdl 的初始化、渲染器和窗口的创建等放在一个类中。您的问题已经得到解答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-20
      • 2015-09-15
      • 2018-04-16
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多