c++ - 类作为函数c++的参数

标签 c++ class parameters function-parameter

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

编辑:

这是我想要完成的

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 - 您不知道也不关心您使用的是哪种特定算法,只是它实现了所有加密算法的接口(interface)应该实现。

关于c++ - 类作为函数c++的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240944/

相关文章:

java - 调用方法 ".class expected"

powershell - TeamCity 无法识别配置参数

java - TestNG中数据参数化的优化方式

c++ - 为什么我的翻译矩阵需要转置?

c++ - 如何在不删除字符的情况下将 SQLCHAR[200] 类型转换为 std::string?

javascript - 用 TypeScript 编写的具有 protected /私有(private)字段的类可以从 JavaScript 中的类外部访问吗?

java - 什么是 Java 中的应用程序级类?

bash - 为 bash 函数参数分配新值

c++ - 防止反向工程 C++ 二进制文件

c++ - 模板特化需求