在c++类中初始化大量变量
Initializing a large number of variables in a C++ class
下面的代码是一段未完成的代码,因为我仍然不完全熟悉如何在c++中使用类,我需要一些关于如何初始化类定义开头所显示的大量整数的指导,stackoverflow的许多人建议我不要为所有这些变量使用构造函数。我可以用什么,怎么用?为什么我不应该用构造函数初始化许多变量?
我最终想要实现的是计算出RSA算法中c的整数,我想为三个用户做这件事。因此,程序为每个生成2个密钥。
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <boost/dynamic_bitset.hpp>
using namespace std;
class LFSR:
{
int y = 0;
int turnCount = 0;
int count1 = 0, count0 = 0;
int xx = 0;
int polyLoc;
int p = 0;
int q = 0;
int d = 0;
int n = 0;
int end = 0;
int f = 0;
int e = 0;
int m = 0;
int c = 0;
int l = 0, g = 0;
boost::dynamic_bitset<> inpSeq(5);
boost::dynamic_bitset<> operSeq(5);
boost::dynamic_bitset<> bit(5);
vector <int> xorArray;
vector <int> keyReg;
public:
LFSR ();
int key ()
{
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
sort(xorArray.rbegin(), xorArray.rend());
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[seq_end] = operSeq[x];
y = xorArray[r];
bit[seq_end] = bit[seq_end] ^ operSeq[y];
}
operSeq >>= 1;
operSeq[seq_end] = bit[seq_end];
keyReg.push_back(operSeq[0]);
turnCount ++;
}
while ((operSeq != inpSeq) && (turnCount < 1024));
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
m = m + int(pow(2,i));
}
}
n = p*q;
f = (p-1)*(q-1);
for (int k = 0; end < 1; k++)
{
if ( (1+k*f)%d == 0)
{
end = 2;
e = (1+(k*f))/d;
}
}
g = int(pow(m,e));
c = g%n;
return c;
}
};
LFSR::LFRS()
{
}
int main ()
{
}
由于p、q和d是变量,而所有其他变量都是不变量(至少在构造过程中),您将希望为用户提供在构造函数中设置变量的机会。
像这样:
LFSR::LFSR(int p_, int q_, int _d)
: p(p_)
, q(q_)
, d(d_)
{
}
在类定义中设置不变量将适用于c++11,而不适用于c++98。
如果你有一个旧的编译器,你需要这样做:
LFSR::LFSR(int p_, int q_, int d_)
: y(0)
, turnCount(0)
// ... all other member variables in order of definition ...
, p(p_)
, q(q_)
, d(d_)
, n(0)
// ... all the rest here ...
{
}
和上面说的一样@AbhiP使用初始化列表
class Baz
{
public:
Baz( std::string foo ) : foo( foo ) { }
private:
std::string foo;
};
如果你使用c++11兼容的编译器,你可以使用In-class成员初始化器。
class A
{
public:
int a = 7;
};
相关文章:
- 为什么C++有不同的变量初始化方式?
- 静态 constexpr 成员变量初始化
- C++不同的变量初始化
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 是变量初始化失败吗?
- 视觉C++:在 DLL 加载期间,全局变量初始化顺序是否具有确定性?
- 类静态变量初始化顺序
- 使用 constinit 变量初始化 constexpr 变量
- 是否可以在不修改父类的情况下将成员变量初始化推迟到继承的类?
- 使用全局变量初始化不同编译单元中的其他全局变量
- 使用默认构造函数引用成员变量初始化错误
- 宏的 if 语句中的变量初始化
- 不稳定的C :每行适应性变化多变量初始化
- 同一函数中的静态函数变量初始化顺序
- C 语言中的静态变量初始化
- 错误:调用'begin(long double [nPoints])'没有匹配函数;使用硬编码的 int 与整数变量初始化向量
- 类POD成员变量初始化
- 尝试捕获类变量初始化的范围
- 共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
- 多变量初始化编译器支持