c++ - 在 C++ 类中初始化大量变量

标签 c++ class

下面的代码是一个未完成的代码,因为我仍然不完全熟悉如何在 C++ 中使用类,我需要一些关于如何在类定义的 shown int 开头初始化大量整数的指导,很多人stackoverflow 的这里建议我不要对所有这些变量使用构造函数。我可以使用什么以及如何使用?为什么我不应该使用构造函数初始化许多变量?

我最终想要实现的是计算 RSA 算法中的 c 的整数,我想为三个用户做这件事。以便程序为每个 key 生成 2 个 key 。

#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 ...
{
}

关于c++ - 在 C++ 类中初始化大量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576303/

相关文章:

c++ - 声明指针变量的不同类型

c++ - 错误 C2143 : syntax error : missing ';' before '.'

c++ - 确定是否可以用单个三角形扇形绘制二维多边形

Javascript:在类内分配onclick

java - 使用扫描仪和嵌套for循环在java中创建空心矩形

Python:发生不需要的变量更改

c++ - 显示二进制加法后的最后一位

c++ - 如何在 Cython 中正确管理 C++ 对象的生命周期?

c++ - 创建 SQLite 类

c++ - C++ 中的不可变类