[英]C++ Different constant member in each derived class, how to move function to remove duplication in access?
我派生了一些常量屬性不同的類。 在所有派生類中,我有一個返回屬性的函數。 有沒有辦法將get_x函數移動到基類中以刪除重復? 我已經看過這個帖子和很多谷歌搜索,但我找不到我想要的東西: C ++:在派生類中初始化基類常量靜態變量具有不同的值?
class Derived1: public Base{
static const attribute x = SOME_ATTRIBUTE1;
attribute get_x(){
return x;
}
};
class Derived2: public Base{
static const attribute x = SOME_ATTRIBUTE2;
attribute get_x(){
return x;
}
};
我希望它看起來像這樣,但這不起作用,因為x沒有在base中定義。 我也嘗試了extern,static const屬性x等。
class Derived1: public Base{
static const attribute x = SOME_ATTRIBUTE1;
};
class Derived2: public Base{
static const attribute x = SOME_ATTRIBUTE2;
};
class Base{
attribute get_x(){
return x;
}
};
謝謝。
有點kludgy,但你可能會使用類似於以下的東西來做到這一點:
template <attribute x> class Base
{
public:
attribute get_x ( ) { return x; }
};
class Derived1 : public Base<SOME_ATTRIBUTE_1>
{
...
};
class Derived2 : public Base<SOME_ATTRIBUTE_2>
{
...
};
與Karl的答案類似,但保留了繼承/派生的關系(好吧,差不多 - 請參閱下面的@ visitor的評論)。
另一方面,有沒有理由不做簡單的覆蓋? 例如:
class Base
{
public:
virtual attribute get_x ( ) = 0;
};
class Derived1 : public Base
{
public:
attribute get_x ( ) { return SOME_ATTRIBUTE_1; };
};
class Derived2 : public Base
{
public:
attribute get_x ( ) { return SOME_ATTRIBUTE_2; };
};
編輯:請注意,模板方法可以擴展到所需的多個屬性,如下所示:
template <attribute1 x, attribute2 y ...> class Base
{
public:
attribute get_x ( ) { return x; }
attribute get_y ( ) { return y; }
...
};
每個屬性都是該類屬性的另一種解決方案可以如下:
class Base
{
public:
Base (attribute newX) : x(newX) { }
attribute get_x ( ) { return x; };
protected:
const attribute x;
};
class Derived1 : public Base
{
public:
Derived1 ( ) : Base(SOME_ATTRIBUTE_1) { }
};
class Derived2 : public Base
{
public:
Derived2 ( ) : Base(SOME_ATTRIBUTE_2) { }
};
在這里,每個Derived
都有一個該類唯一的常量屬性。 如果您願意,您當然可以刪除const
。
好吧,根據類的其余部分,它可能是一個很好的用例,而不是多態繼承:
template <attribute X>
class Base{
attribute get_x(){
return X;
}
}
typedef Base<SOME_ATTRIBUTE1> Derived1;
typedef Base<SOME_ATTRIBUTE2> Derived2;
#include <iostream>
#include <typeinfo>
enum attribute {SOME_ATTRIBUTE1, SOME_ATTRIBUTE2};
class Base
{
public:
virtual attribute get_x() = 0;
};
template <attribute Attr>
class Derived : public Base
{
public:
virtual attribute get_x() {return Attr;}
};
typedef Derived<SOME_ATTRIBUTE1> Derived1;
typedef Derived<SOME_ATTRIBUTE2> Derived2;
int main()
{
std::cout << typeid(Derived1().get_x()).name() << '\n';
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.