C++ 类作为函数c+的参数+;
我以类的形式编写了一系列加密算法,现在我想实现加密模式(wikipedia中显示的通用模式,而不是算法规范中的特定模式)。如何编写一个可以接受任何类的函数 编辑: 以下是我想要实现的目标C++ 类作为函数c+的参数+;,c++,class,parameters,function-parameter,C++,Class,Parameters,Function Parameter,我以类的形式编写了一系列加密算法,现在我想实现加密模式(wikipedia中显示的通用模式,而不是算法规范中的特定模式)。如何编写一个可以接受任何类的函数 编辑: 以下是我想要实现的目标 class mode{ private: algorithm_class public: mode(Algorithm_class, key, mode){ algorithm_class = Algorithm_class(key, mode); } };
class mode{
private:
algorithm_class
public:
mode(Algorithm_class, key, mode){
algorithm_class = Algorithm_class(key, mode);
}
};
嗯,怎么样
template<class AlgorithmType>
class mode{
private:
AlgorithmType _algo;
public:
mode(const AlgorithmType& algo)
: _algo(algo) {}
};
嗯,怎么样
template<class AlgorithmType>
class mode{
private:
AlgorithmType _algo;
public:
mode(const AlgorithmType& algo)
: _algo(algo) {}
};
您可以使用抽象类:
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);
...
//
类加密算法
{
公众:
//无论所有算法都执行什么函数
虚拟向量加密(向量)=0;
虚拟向量解密(向量)=0;
虚空设置键(向量)=0;
//等
}
//用户算法
DES类:公开密码算法
{
//实现加密、解密、设置密钥等
}
//你的职能
类模式{
公众:
模式(CryptoAlgorithm*algo)/您可以使用抽象类:
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);
...
//
类加密算法
{
公众:
//无论所有算法都执行什么函数
虚拟向量加密(向量)=0;
虚拟向量解密(向量)=0;
虚空设置键(向量)=0;
//等
}
//用户算法
DES类:公开密码算法
{
//实现加密、解密、设置密钥等
}
//你的职能
类模式{
公众:
mode(CryptoAlgorithm*algo)//我很想猜测并说“使用模板”,但这实际上取决于您打算对该类执行什么操作。我尝试了模板,但它不起作用。我将编辑我的帖子以展示我想要做的事情。我认为最好的解决方案是创建一个基本抽象算法类,并使您的所有实现都从中继承。什么类型的算法\u类
(它是算法\u class
还是什么的)?如果你真的想传入一个“类作为参数”,您需要使用模板。但正如其他人所指出的,标准的OO方法只是使用继承。创建抽象基类;创建特定的算法作为派生类;让调用方创建特定加密算法的实例,并将其传递给模式
构造函数。我很想猜测一下“使用模板”,但这实际上取决于你打算对类做什么。我尝试了模板,但它不起作用。我将编辑我的帖子来说明我想做什么。我认为最好的解决方案是创建一个基本的抽象算法类,并使你的所有实现都从中继承。什么类型的算法\u类
(它是Algorithm\u class
还是什么的)?如果你真的想传入一个“类作为参数”“,您需要使用模板。但正如其他人所指出的,标准的OO方法只是使用继承。创建抽象基类;创建特定的算法作为派生类;让调用方创建特定加密算法的实例,并将其传递给模式
构造函数。”。