我如何防止函数中的参数过多.C++ [英] How I prevent having too much parameters in a function. C++

查看:35
本文介绍了我如何防止函数中的参数过多.C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C++ 和 Opengl 制作游戏引擎.我制作了一个小游戏来测试我不完整的引擎.但是添加了Camera、Renderder、Level、Player、Zombie和Human等类后,My Player类的函数参数变长了大约8个参数,因为玩家需要与许多类交互,例如Camera、Renderder、Zombie、Human等.

I am making a game engine with C++ and Opengl. I making a small game to test my incomplete engine. But after adding classes like Camera, Renderder, Level, Player, Zombie and Human, My Player class's function parameters getting long about 8 arguments because player needs to interact with many classes like Camera, Renderder, Zombie, Human, etc.

请给出解决此问题的建议或者这才是制作游戏的正确方式.

Please give suggestions to solve this problem Or this is the right way to make games.

推荐答案

没有更多上下文很难说.然而,一个极端是将所有需要作为参数的东西捆绑到一个单一的结构中:

Difficult to say without more context. However, one extreme is to bundle everything needed as parameter into a single struct:

 struct GameContext {
      Camera camera;
      Renderer renderer;
      Level level;
      Player player;
      //...
 };

然后将其作为单个参数传递:

and then pass that as single parameter:

 void foo(const GameContext& context);

然而,这是否可行不仅取决于您希望将该结构作为参数传递的函数.相反,您必须考虑更多,以决定什么属于一起,什么不属于.有时另一个极端(传递 8 个单独的参数)可能是正确的.如果那个函数是这 8 个参数唯一出现的地方,那么你不会为了调用那个函数而将它们放在一个结构体中.

However, whether this is feasible depends not only on the function that you want to pass that structure as parameter. Rather you have to consider more than that to decide what belongs together and what not. Sometimes the other extreme (passing 8 individual parameters) can be the right thing. If that function is the only place where those 8 parameters appear together, then you would not put them in a struct merely to call that one function.

总而言之,我认为您正试图在错误的抽象级别上修复某些内容.考虑整个架构以及您的对象应该如何相互交互.CameraRenderer 不是我希望经常传递的东西.您只需要告诉 Player 一次他们应该使用什么 Camera(如果有的话),而不是每次您调用 Player 的方法之一时.

To summarize, I think you are trying to fix something at the wrong abstraction level. Consider the whole architecture and how your objects are supposed to interact with each other. A Camera or a Renderer is not something I would expect to be passed around that often. You need to tell a Player only once what Camera they should use (if at all) not every time you call one of Players methods.

这篇关于我如何防止函数中的参数过多.C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆