我已经尝试解决我的问题2天了,并且悲惨地失败了。互联网没有帮助。
我要做的是传达两个属于另一个类的类。 这是我的第一个“大”项目,所以我认为我的设计对你们来说很糟糕。 此外,我的程序在很多文件之间分开,可能会令人困惑。
让我们击中它!为了便于阅读,我将每个成员都改为公开。 这是我的MainOGLController类,它是控制程序所有内容的主类:
class MainOGLController
{ // I deleted constructor/destructor from this quote
public:
DisplayController* Display;
StellarManager* Manager; // it will need to use something from Display
void RenderScene();
bool CreateNewDisplay(int, char*[]); // argc argv
}
好的,这就是我用main()创建这个类的实例的方法:
#include "MainOGLController.h"
MainOGLController Controller;
int main(int argc, char* argv[])
{
if ( Controller.CreateNewDisplay(argc, argv) ) return 1; // if it fails then exit;
// some opengl code here
return 0;
}
现在您可能想知道CreateNewDisplay方法如何:
bool MainOGLController::CreateNewDisplay(int argc, char* argv[])
{
Display = new DisplayController(argc, argv);
Manager = new StellarManager(&Display); // me trying to make reference to Display
// to be able to use it within Manager
//ogl code
else return 0;
}
好的,所以我在那里创建了Manager,现在我们应该看看我是如何创建StellarManager类的:
class StellarManager
{
std::vector<Stellar*> VectorManager; // objects from this vector will need to use
// ptrDisplay to access Display
DisplayController* ptrDisplay;
StellarManager(DisplayController&);
void addEntity();
};
现在为构造函数:
StellarManager::StellarManager(DisplayController& _p) // me trying to do anything
{
*ptrDisplay = _p;
}
所以在这一点上我应该有MainOGLController的实例,并且在其中有一个指向DisplayController和StellarController的指针,其中StellarController应该有自己的指向同一个DisplayController的指针。
现在我正在使用一段代码来调用addEntity方法:
void StellarManager::addEntity()
{
VectorManager.push_back(new Stellar(&ptrDisplay); // sending ptrDisplay so that the
// Stellar object can use it
}
Stellar类的定义如下:
class Stellar
{
public:
DisplayController* ptrDisplay;
Stellar(DisplayController**);
void Draw(); // finally, heres where i want to use this Display pointer
};
Stellar构造函数:
Stellar::Stellar(DisplayController** _p)
{
*ptrDisplay = **_p;
}
OKAY!那是最后一块。我现在要做的只是调用方法Draw,它属于Stellar类,并使用位于MainOGLController中的Display。
Manager->VectorManager[0].Draw();
哦,Draw看起来就像这样:
void Stellar::Draw(int _mode)
{
GLMatrixStack* mvm = &(ptrDisplay->modelViewMatrix);
mvm->Scale(2, 0.5, 0.5); // Scale is a method from GLMatrixStack
}
多数民众议员,如果有更好的办法,我会全力以赴。 我做的不起作用,我可以使用Stellar类的* ptrDisplay,但没有任何反应,所以我想我没有使用它的引用而是副本。
抱歉,我知道这是很多代码,可能会让人很困惑。我现在不知道该怎么办......
答案 0 :(得分:0)
看起来问题就在这里:
Stellar::Stellar(DisplayController** _p)
{
*ptrDisplay = **_p;
}
您取消引用从未初始化的指针(ptrDisplay
)。这会导致未定义的行为。我认为这抓住了你想做的事情:
Stellar::Stellar(DisplayController* _p) : ptrDisplay(_p)
{
}
没有必要将指针传递给 - DisplayController
;您的所有Stellar
类需求都是指向DisplayController
的指针。此外,听起来您不想取消引用_p
并复制它,因此只需复制指针(通过ptrDisplay(_p)
)将导致ptrDisplay
指向与{{_p
相同的对象1}}。