C++ 如何在没有循环依赖的情况下从对象访问方法?
C++ how to access a method from object without having circular dependencies?
我有:
一个 class 游戏包含:
- 对 class OpenGLManagement
的引用
- 一件std:vector件
一篇 class 篇文章包含:
- 一种旋转()棋子的方法
一个 class OpenGLManagement 包含:
- 一个方法 doStuff()
类似这样的事情(我只是留下了对提问有用的代码):
class Piece
{
public:
void rotate(); //rotate this piece
}
class OpenGLManagement
{
public:
doStuff(); //How can I access the rotate() function on the Piece class?
}
class Game
{
public:
Game(OpenGLManagement& openGLObj) : m_openGL(openGLObj) {}
private:
OpenGLManagement& m_openGL; //a reference to my object
std::vector<Piece> m_pieces; //my vector of pieces
}
int main()
{
OpenGLManagement myOpenGL;
Game myGame(myOpenGL);
//...etc
return 0;
}
我的objective:
如何从 doStuff() 函数访问 Piece class 上的 rotate() 函数?
can/should 我对代码进行了哪些更改以在良好的 C++ 实践中实现该目标?:)
我想通过引用指向任何地方来避免循环依赖。此外,我需要先创建 myOpenGL 对象...所以我还不知道对 Game 对象的引用...
谢谢!
只需将 Piece
class 置于其他之上即可。
如果正确组织include,就不会有循环依赖。您不需要 OpenGlManagment
class 来定义 Piece
,也不需要 'Piece' 来定义 OpenGlManagment
class。至少我从你的代码中是这样认为的。如果您将函数定义放在 *.cpp 文件中,并且只将 class 定义和前向声明放在适当的 *.h 文件中,那么一切都应该没问题。像这样:
Piece.h
class Piece
{
public:
void rotate(); //rotate this piece
}
Piece.cpp
#include "Piece.h"
void Piece::rotate(){
//definition here
}
OpenGlManagment.h
class Piece;
class OpenGLManagement
{
public:
void doStuff();
}
OpenGlManagment.cpp
#include "OpenGlManagment.h"
#include "Piece.h"
void OpenGLManagement::doStuff(){
//use your Piece methods here
}
创建了一个 class,用静态对象实例化了另外两个。
然后我为引用创建了两个get方法。
我有:
一个 class 游戏包含:
- 对 class OpenGLManagement 的引用
- 一件std:vector件
一篇 class 篇文章包含:
- 一种旋转()棋子的方法
一个 class OpenGLManagement 包含:
- 一个方法 doStuff()
类似这样的事情(我只是留下了对提问有用的代码):
class Piece
{
public:
void rotate(); //rotate this piece
}
class OpenGLManagement
{
public:
doStuff(); //How can I access the rotate() function on the Piece class?
}
class Game
{
public:
Game(OpenGLManagement& openGLObj) : m_openGL(openGLObj) {}
private:
OpenGLManagement& m_openGL; //a reference to my object
std::vector<Piece> m_pieces; //my vector of pieces
}
int main()
{
OpenGLManagement myOpenGL;
Game myGame(myOpenGL);
//...etc
return 0;
}
我的objective:
如何从 doStuff() 函数访问 Piece class 上的 rotate() 函数?
can/should 我对代码进行了哪些更改以在良好的 C++ 实践中实现该目标?:)
我想通过引用指向任何地方来避免循环依赖。此外,我需要先创建 myOpenGL 对象...所以我还不知道对 Game 对象的引用...
谢谢!
只需将 Piece
class 置于其他之上即可。
如果正确组织include,就不会有循环依赖。您不需要 OpenGlManagment
class 来定义 Piece
,也不需要 'Piece' 来定义 OpenGlManagment
class。至少我从你的代码中是这样认为的。如果您将函数定义放在 *.cpp 文件中,并且只将 class 定义和前向声明放在适当的 *.h 文件中,那么一切都应该没问题。像这样:
Piece.h
class Piece
{
public:
void rotate(); //rotate this piece
}
Piece.cpp
#include "Piece.h"
void Piece::rotate(){
//definition here
}
OpenGlManagment.h
class Piece;
class OpenGLManagement
{
public:
void doStuff();
}
OpenGlManagment.cpp
#include "OpenGlManagment.h"
#include "Piece.h"
void OpenGLManagement::doStuff(){
//use your Piece methods here
}
创建了一个 class,用静态对象实例化了另外两个。 然后我为引用创建了两个get方法。