2015-12-15 99 views
2

我有這樣的鹼和這些派生類C++:訪問父類

class AlarmType 
{ 
    public: 
     unsigned int alarmIndex; 
}; 

class TrendAlarmType : public AlarmType 
{ 
    public: 
     typedef enum 
     { 
      decreasing = 0, //will be used as index apart from enum 
      steady, 
      increasing 
     } Trend_types; 

     Trend_types alarmIndex2; 
}; 

class ThresholdAlarmType : public AlarmType 
{ 
    public: 
     typedef enum 
     { 
      low = 0, //will be used as index apart from enum 
      lowmid, 
      highmid, 
      high, 
     } Threshold_types; 

     Threshold_types alarmIndex3; 
}; 

這裏alarmIndex2alarmIndex3是不同類型的的構件,從而AlarmType::alarmIndex不應該存在。 是否可以聲明模板 理想情況下,alarmIndex將是基類的模板成員,alarmIndex2 & 3將不存在。可能嗎?我想實現AlarmType爲模板類

template< typename T> 
class AlarmType 
{ 
    public: 
     unsigned int alarmIndex; 
}; 

,然後嘗試從派生類訪問alarmIndex如下

alarmIndex<Trend_types> = tt; OR 
alarmIndex<Threshold_types> = tt; 

我得到的大量啓動了「錯誤的錯誤:預期「{」令牌」上線

class TrendAlarmType : public AlarmType 
{ ... 

,如果我嘗試添加型我想

之前類名
class TrendAlarmType : public AlarmType<Trend_types> 
{ ... 

Trend_types尚未申報。所以我陷入了其他麻煩。有沒有辦法在基類中聲明變量?

謝謝

+0

那麼,你的主要錯誤是你忘記用分號終止你的類聲明。先做,然後看看還有什麼錯誤。 – paddy

+0

它從來沒有在代碼上的錯誤。我只是沒有從我的文件複製一切。修正了這裏的條目,以避免混淆。 – nass

+0

我覺得有些事情......對你管理問題的方式很陌生。對於繼承,看起來好像你不能刪除繼承類的一部分,而是在不對基類的報警索引類型進行頂級替換的情況下替換它。理想的方法是在實例化類時提供枚舉類型,然後在名稱空間,頭部或代碼部分可訪問的某處存在枚舉。 – VermillionAzure

回答

1

我不是你要完成的100%清楚,但我相信你要找的究竟是不是繼承,但模板走樣,這是在C++ 11引入(一個C++ 11的編譯器支持是必需的):

typedef enum 
     { 
     decreasing = 0, //will be used as index apart from enum 
     steady, 
     increasing 
     } Trend_types; 

typedef enum 
     { 
     low = 0, //will be used as index apart from enum 
     lowmid, 
     highmid, 
     high, 
     } Threshold_types;  

template<typename T> using alarmIndex=T; 

這使得可以使用下面的語法:

alarmIndex<Trend_types> t1 = decreasing; 
alarmIndex<Threshold_types> t2 = lowmid; 

這似乎是您要的政績語法根據你的問題。

但是,讓我們更進一步,並使用枚舉類的強制類型安全:

enum class Trend_types 
{ 
    decreasing = 0, //will be used as index apart from enum 
    steady, 
    increasing 
}; 

enum class Threshold_types 
{ 
    low = 0, //will be used as index apart from enum 
    lowmid, 
    highmid, 
    high, 
}; 

template<typename T> using alarmIndex=T; 

// ... 

alarmIndex<Trend_types> t1 = Trend_types::decreasing; 
alarmIndex<Threshold_types> t2 = Threshold_types::lowmid; 

隨着枚舉類,編譯器將強制類型安全,並會拒絕嘗試給一個Threshold_types值到Trend_types實例(自己嘗試)。

請注意,模板別名是通用的,將爲這個語法糖提供任何類,而不僅僅是這兩個。

如果您真的想這樣做,只需要更多的工作就可以限制模板別名僅與這兩個類一起工作。