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

查看:284
本文介绍了如何防止函数中包含过多参数.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.

总而言之,我认为您正在尝试以错误的抽象级别修复某些内容.考虑整个体系结构以及对象之间的交互方式.我不希望经常将 Camera Renderer 传递出去.您只需要告诉一次 Player 一次(如果有的话),而不是每次您调用 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天全站免登陆