Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在c+中实现组件模式时的耦合+;提供_C++_Oop_Design Patterns_Components_Game Engine - Fatal编程技术网

C++ 在c+中实现组件模式时的耦合+;提供

C++ 在c+中实现组件模式时的耦合+;提供,c++,oop,design-patterns,components,game-engine,C++,Oop,Design Patterns,Components,Game Engine,现在,我有一个类,其中包含一些组件来做一些事情,而这些组件也需要父类的引用来更新状态。它们相互耦合使得设计很困难。下面是一个示例代码片段: #include<iostream> #include <windows.h> #include <math.h> using namespace std; class man { public: int health{ 10 }, x, y; void update(); private: cla

现在,我有一个类,其中包含一些组件来做一些事情,而这些组件也需要父类的引用来更新状态。它们相互耦合使得设计很困难。下面是一个示例代码片段:

#include<iostream>
#include <windows.h>
#include <math.h>
using namespace std;
class man {
public:
    int health{ 10 }, x, y;
    void update();
private:
    class moveCom *_move;
    class judgeCom *_judge;
};
class moveCom {
public:
    void update(man&m) {
        ++m.x;
        ++m.y;
    }
};
class judgeCom {
public:
    void update(man&m) {
        if(rand()%10 <= 5)
            ++m.health;
        else --m.health;
    }
};
void man::update() {
    _move->update(*this);
    _judge->update(*this);
    cout << health << " " << x << " " << y << endl;
}
int main() {
    man m;
    while (1) {
        Sleep(200);
        m.update();
    }
    return 0;
} 
#包括
#包括
#包括
使用名称空间std;
班主任{
公众:
int-health{10},x,y;
无效更新();
私人:
类moveCom*\u move;
类别法官首席法官;
};
类moveCom{
公众:
无效更新(man&m){
++m、 x;
++m、 y;
}
};
阶级法官{
公众:
无效更新(man&m){
如果(rand()%10更新(*此);
_判断->更新(*此);

cout separate to file应该没有区别。您的
判断Com
s只能接受当前运行状况作为参数,根据计算新值并返回。x和y可以打包到结构
坐标中,然后作为引用传递给moveCom进行修改。这样,两个
Com
s就不会必须了解
。仍然很简单但更好的方法是创建一个基本
组件
(带有虚拟析构函数和更新函数)并在
man
中存储一个唯一的ptr列表,然后让每个组件派生您的组件类,然后在创建新组件时添加一个指向其基的指针到您的组件lis。然后您可以迭代该列表并调用所有您想要的组件的更新,而无需手动添加条目。您还可以执行其他操作同时,面向数据的设计,特别是实体组件系统也在游戏开发社区中得到了广泛的关注。