我正在尝试构建一个类,使其子类具有 C++11enum class
属性,并具有关联的 setter/getter:
class Base {
public:
enum class MyEnum {
A,
B
} my_enum;
Base() : my_enum(MyEnum::A) {}
MyEnum get() { return my_enum; }
void set(const MyEnum &ME) { my_enum = ME; }
};
class Derived : public Base {
public:
Derived(): Base() {
my_enum = MyEnum::B;
}
};
int main(int argc, char *argv[])
{
Derived Deriv;
// No problems!
Deriv.get() == Derived::MyEnum::B;
return 0;
}
到目前为止,一切都很好!
但是,我希望派生类能够重新定义MyEnum
枚举类,而不必一直重新实现 setter/getter/attribute:
// Base as before
class Derived : public Base {
public:
enum class MyEnum {
C,
D
}; // intention: to override Base's "my_enum" attribute
Derived(): Base() {
my_enum = MyEnum::C;
// ERROR: cannot convert 'Derived::MyEnum' to 'Base::MyEnum'
}
};
int main(int argc, char *argv[])
{
Derived Deriv;
// ERROR: no match for 'operator==' for types 'Base::MyEnum' and 'Derived::MyEnum'
Deriv.get() == Derived::MyEnum::C;
return 0;
}
我了解问题所在;我只是在寻找能够在这种情况下重用代码的最干净的方法。
最好仅通过继承(或者更确切地说,该功能应该仅通过从 Base() 派生的行为对 Derived() 类可用)。
有什么建议么?