jke*_*ian 3 c++ polymorphism static const
我有一个相当奇怪的情况,我希望能够定义ABC的子类可以覆盖的某些常量.
struct A {
static const int a = 20;
virtual int func() = 0;
};
struct B : public A {
static const int a = 3;
int func() { return 5; }
};
struct C : public A {
static const int a = 4;
int func() { return 3; }
};
Run Code Online (Sandbox Code Playgroud)
不幸的是,如果我使用A *aPtr = new B
,aPtr->a
将返回20,而不是3.
我看到的一个解决方法是单行函数(沿着上例中的行func
),但是常量的语法在概念上更适合于这种特殊情况.是否有一种语法上合理的方法来解析在运行时使用哪些常量,其中调用代码在创建初始对象后不需要知道任何内容?
常量,尤其是静态常量,不能像你要求的那样被覆盖.您将不得不使用虚拟功能:
struct A {
virtual int get_a() { return 20; }
int func() = 0;
};
struct B : public A {
virtual int get_a() { return 3; }
int func() { return 5; }
};
struct C : public A {
virtual int get_a() { return 4; }
int func() { return 3; }
};
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用常量模板:
template< const int a_value = 20 >
struct A {
static const int a = a_value;
int func() = 0;
};
struct B : public A<3> {
int func() { return 5; }
};
struct C : public A<4> {
int func() { return 3; }
};
Run Code Online (Sandbox Code Playgroud)