【问题标题】:How to call a random function of a class in c++?如何在 C++ 中调用类的随机函数?
【发布时间】:2021-03-12 11:51:57
【问题描述】:

我正在尝试在C++ 中创建一个命令行游戏。我是新手,刚开始学习。 我的游戏由玩家类和龙类组成。这些类在单独的头文件中声明。 我想知道的是,是否有办法在声明后调用类的随机函数。
喜欢

// ignore the includes
class foo{
    public:
        string name = "foo";
        foo(string name){
            this->name = name;
        }

        void func1(){
            //some code
        }

        void func2(){
            //some code
        }

        void func3(){
            //some code
        }
}


/////
//main.cpp
#include <iostream>
#include "foo.h"

int main(){
    foo bar("hello");
    //call a random function like func1, func2, func3;
    return 0;
}

【问题讨论】:

  • 你可以使用 switch(randomNumber) { case 1: func1();休息; ...或使用函数指针数组。

标签: c++ function random header


【解决方案1】:

我自己也是一个初学者,我相信有比我更容易/更好的解决方案。

你可以试试看。

int random_val = rand();
int nr = random_val % 3; 
switch (nr) {
    case 0: bar.func1();
            break;
    case 1: bar.func2();
            break;
    case 2: bar.func3();
            break;
    default:
            std::cout << "Default case" << std::endl;
} 

【讨论】:

  • 感谢您的回答。通常最好将您的答案构建为陈述而不是问题。我已经编辑以显示我的意思。希望没问题。
【解决方案2】:

您可以使用给定的函数创建一个数组,并生成一个随机 int 作为数组的索引:

void invoke_random_function(foo& bar)
{
    //make an array of pointers to desired functions
    using func_type = void(foo::*)();
    constexpr func_type funcs[] = {
        &foo::func1,
        &foo::func2,
        &foo::func3
    };
    
    //select a random function from array
    auto random_index = (std::rand() % std::size(funcs)); //use better RNG than std::rand if necessary
    auto random_func = funcs[random_index];

    //invoke the selected function with the given instance of the class         
    (bar.*random_func)(); //funny notation to invoke member function pointers
}

【讨论】:

  • 更好的是使用 std::vector 或 std::array (这样大小是一个简单的成员函数调用)和 std::functions 而不是原始函数指针,以便调用语法并不那么神秘。
  • 你能解释一下如何提供一个数组并在main中调用invoke函数,因为我是一个初学者,我还不懂指针。
  • 要从main调用invoke_random_function,你只需执行foo bar("hello"); invoke_random_function(bar);,然后一个随机函数就会被调用。我不明白你所说的“如何提供数组”是什么意思,你能详细说明一下吗?
  • 没关系,我知道怎么做,但是你说“你可以用给定的函数做一个数组”,所以我很困惑,谢谢
猜你喜欢
  • 1970-01-01
  • 2020-12-26
  • 2011-07-22
  • 2015-02-10
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 2010-12-25
相关资源
最近更新 更多