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

Initializing a large number of variables in a C++ class

本文关键字:变量 初始化 c++      更新时间:2023-10-16

下面的代码是一段未完成的代码,因为我仍然不完全熟悉如何在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;
};