传递枚举类型作为参数?c++

Passing an enum type as a parameter? c++

本文关键字:参数 c++ 枚举 类型      更新时间:2023-10-16

例如,我在一个函数中创建一个enum,并将它们保存在动物类型的数组中,在本例中只是奶牛值,然后我想将该数组传递给function2作为参数,我该如何做呢?

void function1()
{
    enum animals{cow,cat,dog};
    animals array[3];
    for(int i=0;i<3;i++)
    {
        array[i]=cow;
    }
    function2(array);
} 
void function2()
{
    // blablabla
}

enum定义必须对两个函数都可见。例如:

enum animals{cow,cat,dog};
template<size_t N>
void function2(animals (&foo)[N])
{
    cout << "Received " << N << " animals.n";
}
void function1()
{
    animals array[3] = { cow, cow, cow };
    function2(array);
} 

可以将数组强制转换为int数组并传入:

function2((int*)array);

但是函数2不知道如何解码枚举。如果您希望在多个函数中使用enum,则需要将其定义为全局变量或在两个函数都可以看到的其他位置。