所以我有这样的东西:
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/