Classes as parameter of function c++

半城伤御伤魂 提交于 2019-12-08 03:56:11

问题


I wrote a bunch of crypto algorithms as classes and now I want to implement encryption modes (generalized modes shown in wikipedia, not the specific ones in the algorithms' specifications). How would I write a function that can accept any of the classes?

edit:

here's what i want to accomplish

class mode{
  private:
    algorithm_class

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

    }

};

回答1:


Well, how about

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

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

?

No need for mode and key parameters, as the algorithm can be created by the user:

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



回答2:


You can use abstract classes:

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);
...
//

In this way when you call _algo->Encrypt - you don't know and don't care about which specific algorithm you're using, just that it implements the interface all the crypto algorithms should be implementing.



来源:https://stackoverflow.com/questions/6240944/classes-as-parameter-of-function-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!