2011-06-05 101 views
1

我寫了一堆加密算法作爲類,現在我想實現加密模式(在wikipedia中顯示的通用模式,而不是算法規範中的特定模式)。我將如何編寫一個可以接受任何類的函數?作爲函數參數的類C++

編輯:

這裏就是我要完成

class mode{ 
    private: 
    algorithm_class 

    public: 
    mode(Algorithm_class, key, mode){ 
     algorithm_class = Algorithm_class(key, mode); 

    } 

}; 
+2

我很想去猜測並說「使用模板」,但這實際上取決於你打算如何處理這個類。 – trutheality 2011-06-05 04:09:34

+0

我試過模板,但沒有工作。生病編輯我的帖子,以顯示我想要做 – calccrypto 2011-06-05 04:10:06

+3

我認爲最好的解決方案是創建一個基本的抽象算法類,並使所有的實現繼承它。 – trutheality 2011-06-05 04:15:25

回答

2

那麼,如何

template<class AlgorithmType> 
class mode{ 
    private: 
    AlgorithmType _algo; 

    public: 
    mode(const AlgorithmType& algo) 
     : _algo(algo) {} 
}; 

無需modekey參數,該算法可以由用戶創建的:

mode<YourAlgorithm> m(YourAlgorithm(some_key,some_mode)); 
3

您可以使用抽象類:

class CryptoAlgorithm 
{ 
    public: 
     // whatever functions all the algorithms do 
     virtual vector<char> Encrypt(vector<char>)=0; 
     virtual vector<char> Decrypt(vector<char>)=0; 
     virtual void SetKey(vector<char>)=0; 
     // etc 
} 

// user algorithm 
class DES : public CryptoAlgorithm 
{ 
    // implements the Encrypt, Decrypt, SetKey etc 
} 
// your function 
class mode{ 
public: 
    mode(CryptoAlgorithm *algo) // << gets a pointer to an instance of a algo-specific class 
      //derived from the abstract interface 
     : _algo(algo) {}; // <<- make a "Set" method to be able to check for null or 
         // throw exceptions, etc 
private: 
    CryptoAlgorithm *_algo; 
} 

// in your code 
... 
_algo->Encrypt(data); 
... 
// 

在當你調用_algo->Encrypt這樣 - 你不知道也不關心你正在使用哪種算法,只是它實現了所有加密算法應該實現的接口。