简体   繁体   English

函数返回字符串而不是整数是不是很糟糕? (C ++)

[英]Is it bad to have functions return strings instead of ints? (C++)

I'm still relatively new to programming. 我还是比较新的编程。 I'm in the process of working on a game with SDL and I find myself wondering where or not I am using bad habits. 我正在使用SDL进行游戏,我发现自己想知道我在哪里使用坏习惯。

For example, I have a function called titleScreen(), where the user decides which mode of the game to enter. 例如,我有一个名为titleScreen()的函数,用户可以决定要输入哪种游戏模式。

I can either return a value from 0-3, then process it through an if/else/else/else statement to decide what mode they selected. 我可以从0-3返回一个值,然后通过if / else / else / else语句处理它来决定它们选择的模式。

or 要么

I can return a string such as "STORYMODE", "FREEPLAY", "TUTORIAL", or "QUIT" and use that to decide which mode. 我可以返回一个字符串,如“STORYMODE”,“FREEPLAY”,“TUTORIAL”或“QUIT”,并使用它来决定哪种模式。

I like the second mode because it eliminates the initital confusion on trying to figure out which mode was selected, but I have a feeling in the back of my head that there is a problem doing it that way. 我喜欢第二种模式,因为它消除了试图弄清楚选择了哪种模式的初始混淆,但我感觉在我的脑后这样做是有问题的。

In my situation, what is the best way to return a value? 在我的情况下,返回值的最佳方法是什么?

In this case you should use enum listing all states to achieve readability without performance hit. 在这种情况下,您应该使用列出所有状态的enum来实现可读性而不会影响性能。 For example: 例如:

enum  mode {
    STORYMODE,
    FREEPLAY,
    TUTORIAL,
    QUIT
}

You should use enums for that, that is actually int but just more readable. 你应该使用枚举,实际上是int但更具可读性。 So I would create: 所以我会创建:

enum GameMode { STORYMODE, FREEPLAY, TUTORIAL, QUIT };

And have method return type GameMode. 并且有方法返回类型GameMode。

EDIT 2: 编辑2:

If you have buttons for every game mode, just return enum or call some other method with enum parameter when button is clicked. 如果你有每个游戏模式的按钮,只需返回枚举或单击按钮时使用enum参数调用其他方法。 Same way as you are doing now with string. 与现在使用字符串相同的方式。

What about returning a shared pointer to a game object? 如何返回一个指向游戏对象的共享指针? Below is some pseudo code to get you started and whatever calls titleScreen should call operator() on the returned object. 下面是一些伪代码,可以帮助您入门,以及titleScreen应该在返回的对象上调用operator()任何调用。

class GameI {
public:
    virtual ~GameI() {};
    void operator() = 0;
}

typedef std::shared_ptr<GameI> SharedGame;

class GameStory {
public:
    void operator();
}

void GameStory::operator()
{
    ...
}

SharedGame titleScreen()
{
    ...
    return SharedGame(new GameStory());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM