c – 实现具有枚举和类行为的东西
考虑到我有一些既有枚举又有类行为的“东西”.举个例子,考虑一个具有Color概念的世界,正好有3个:红色,绿色和蓝色.
基于这种颜色,我们也有功能,例如我们可以有一个功能告诉我们颜色是否是一个快乐的颜色,以及一些其他功能: isHappy: Color -> {yes,no} intensity: Color -> value rotate: Color -> Color 要完成类似haskel的语法,我们可以这样做: data Color = Red | Green | Blue 并实现上述功能.但那就是haskell,它不是C而且没有像c那样的OO概念.继续C: 事实上,我们有3种颜色,而不是更多,建议使用枚举;允许我们在源代码中的任何地方使用红色,蓝色和绿色等常量.但是,我们不能将方法添加到枚举中,所以isHappy强度和旋转将实现为函数(而不是方法). 事实上我们有这些方法,其中第一个参数是Color,建议使用类.但是,我们可以实例化我们想要的许多类,特别是超过3.这意味着表示Red的两个变量将分配在内存中的不同位置.这有点奇怪,因为Red会有非常“常量”的行为,因为它是不可变的,只能创建三种不同类型的Color对象.此外,我们不能使用红色,绿色和蓝色等符号,但需要将它们存储在变量中.使用全局变量将是非常丑陋的imho. 我们也可以使用继承,其中Red,Green和Blue继承自Color类.这使我们可以非常轻松地微调功能,因为我们可以在我们想要的任何类中实现我们想要的功能.但是,在c中继承的OO应用切片.例如,创建包含(红色,绿色或蓝色)列表的向量将非常棘手.或者创建一个存储3种颜色之一的变量: Color c1 = Red(); Color c2 = Blue(); 变量c1和c2将被分配一个不同的对象,但是没有办法真正区分它们.这使得实现operator ==棘手: class Red : Color { //... bool operator==(Color &c) const{ // no way to determine whether c is Red,Green or Blue. } } 这种情况是否有有效的模式或解决方案?我觉得它看起来很多,因此我很好奇. C 14-only解决方案也非常受欢迎! 编辑:许多人似乎评论说,我提到的解决方案的问题并不是真正的问题.这是一个有效的观点.但是,我不是在寻找可能的解决方案,我正在寻找一种符合c(11 | 14)设计原则的解决方案.我也可以用: #define RED 0 #define GREEN 1 #define BLUE 2 这将完美无缺,但它不是一个好的设计原则,因为它可能会与其他功能相冲突,使用RED,BLUE或GREEN等名称.这在语义上也很奇怪,因为我可以说RED 总而言之,在答案中,我希望看到一个坚持良好的c设计原则的解决方案.我不关心那些正常工作的解决方案!这可能是前面提到的三种方法之一,使用枚举,一个类或继承. EDIT2:同时我也提到了基于模板的多继承案例.但是,说实话,我对模板的了解还不足以创造出“好”的东西.这个想法基于type_traits标头的std :: is_same和std :: is_functional之类的函数. #include <iostream> class Color {}; class Red : Color {}; class Green : Color {}; class Blue : Color {}; template<class C1,class C2> bool is_same_color(); template<class C1> bool is_happy(); int main() { // your code goes here return 0; } 它不起作用,但我希望这个想法能够实现.另外,我意识到is_same_color和is_happy应该是定义了operator()的类. 编辑3:可以说这是我想要的: enum Color { RED,GREEN,BLUE bool isHappy() { return this==GREEN || this==RED; } Color rotate() { return (this==RED ? GREEN (this==GREEN ? BLUE : RED)); } int intensity() { return (this==RED ? 11 (this==GREEN ? 12 : 4)); } } 但那当然不是有效的c. 解决方法
您可以使用类并使用特定实例(la singleton)作为枚举:
class Color { public: bool isHappy() const { return this == &Green || this == &Red; } const Color* rotate() const { return (this == &Red ? &Green : (this == &Green ? &Blue : &Red)); } int intensity() const {return mIntensity; } static const Color* red() { return &Red; } static const Color* green() { return &Green; } static const Color* blue() { return &Blue; } private: // forbid to construct new instance: use only red(),green(),blue() explicit Color(int intensity) : mIntensity(intensity) {} Color(const Color&) = delete; private: int mIntensity; private: static const Color Red; static const Color Green; static const Color Blue; }; const Color Color::Red(11); const Color Color::Green(12); const Color Color::Blue(4); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |