C++:将未知 union 传递给函数作为参数

标签 c++ struct unions

所以我有这样的东西:

struct FoodType {
    union {
        int fat = 2;
    } Apple;
    union {
        int fat = 3;
    } Banana;
} FoodType;

我想编写一个函数,它接受一个“未知”的 FoodType 作为参数。

void eatFood(FoodType type) { /* do something */ }

如何实现?

最佳答案

您在问题中提供的枚举解决方案的替代方案是实例化:

#include <iostream>

struct FoodType {
    FoodType(int f) : fat(f) {}
    int getFat() { return fat; }
    int fat;
};

void eatFood(const FoodType& type) { std::cout << "I ate " << type.getFat() << " grams of fat\n"; }

int main() {
    FoodType apple(2);
    eatFood(apple);
    FoodType banana(3);
    eatFood(banana);
}

或者,对于更复杂的情况,可以使用多态性,但在这里似乎有点矫枉过正:

#include <iostream>

struct FoodType {
    virtual int getFat() const = 0;
};

struct Apple: FoodType {
    int getFat() const { return 2; }
};

struct Banana: FoodType {
    int getFat() const { return 3; }
};

void eatFood(const FoodType& type) { std::cout << "I ate " << type.getFat() << " grams of fat\n"; }

int main() {
    Apple apple;
    eatFood(apple);
    Banana banana;
    eatFood(banana);
}

关于C++:将未知 union 传递给函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48209219/

相关文章:

c++ - 指向匿名 union 成员的指针是否相等?

c - C 中 union 内的结构

c++ - openGL 在运行时创建纹理图集?

c++ - 将文件内容加载到C++结构中

SWIFT:将 NSData 中的字节粘贴到结构中?

c - c99 中的静态结构初始化

c - 为什么不引发异常?如果枚举大小小于 100 字节

c++ - 为什么信号和槽比普通的旧回调更好?

c++ - 解决将 Qt 与 cmake 一起使用时的链接错误

c++ - 由 4 个十六进制字符组成的数字