类作为函数c++的参数

Classes as parameter of function c++

本文关键字:参数 c++ 函数      更新时间:2023-10-16

我写了一堆加密算法作为类,现在我想实现加密模式(维基百科中显示的通用模式,而不是算法规范中的特定模式)。我该如何编写一个可以接受任何类的函数?

编辑:

以下是我想要完成的

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

您可以使用抽象类:

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时,你不知道也不在乎你使用的是哪种特定的算法,只是它实现了所有加密算法都应该实现的接口。

好吧,怎么样

template<class AlgorithmType>
class mode{
  private:
    AlgorithmType _algo;
  public:
    mode(const AlgorithmType& algo)
      : _algo(algo) {}
};

不需要modekey参数,因为算法可以由用户创建:

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