类作为函数c ++的参数

时间:2011-06-05 04:06:16

标签: c++ class parameters function-parameter

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

编辑:

这就是我想要完成的事情

class mode{
  private:
    algorithm_class

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

    }

};

2 个答案:

答案 0 :(得分: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时 - 你不知道也不关心你正在使用哪种特定算法,只是它实现了所有加密算法应该实现的接口。

答案 1 :(得分: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));
相关问题