【问题标题】:Using a random string generator in c++ constructor [duplicate]在c ++构造函数中使用随机字符串生成器[重复]
【发布时间】:2019-04-07 04:10:31
【问题描述】:

当尝试为类中的名称属性随机生成字符串时,输出似乎为每个对象打印相同的字符串。

当我在调试器中运行它时,会为每个 Array 对象生成一个唯一的名称标识符,但是,在编译和运行程序时,两个对象的名称属性是相同的。任何有关为什么会发生这种情况的帮助将不胜感激。谢谢!

主要:

int main() {
  Array One(3);
  Array Two(5);
  cout << One.getName() << endl;
  cout << Two.getName() << endl;

  return(0);
}

头文件:

public:
   Array(int arraySize= 10);              // default constructor
   Array(const Array &init);              // copy constructor
   ~Array();                              // destructor

   void setName();                          // set objects w/ unique names
   int getCapacity() const;                 // return capacity
   int getNumElts() const;                  // return numElts
   string getName() const;                  // return name
   void incrementNumElts();                 // increment numElts
   void incrementCapacity();                // increment capacity

private:
   int capacity,        // capacity of the array
       numElts;         // Elements in the array in use
   int *ptr;            // pointer to first element of array
   static int arrayCount;   // # of Arrays instantiated
   string name;
};

.cpp 文件中的默认构造函数:

Array::Array(int arraySize) {
  setCapacity(( arraySize > 0 ? arraySize : 10 ));
  setNumElts();
  setName(); /* Giving each object a unique identifier.
              Note: names will be different from the variable names in the
              code. This will just make the prints a bit more clear about
              which objects are being appended, copied etc.. */
  ptr = new int[getCapacity()]; // create space for array
  assert( ptr != 0 );    // terminate if memory not allocated
  ++arrayCount;          // count one more object
}

设置函数:

void Array::setName() {
  srand(time(NULL));
  string Str;

  static const char alphanum[] =
  "0123456789"
  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  "abcdefghijklmnopqrstuvwxyz";


  for(int i = 0; i < 4; ++i) {
    Str += alphanum[rand() % sizeof(alphanum)-1];
  }
  name = Str;
}

get函数:

// Get unique identifier of array object
string Array::getName() const {
  return name;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    您每次都拨打srand(time(NULL))。这为随机数生成器提供了种子。如果您在同一秒内调用它,它具有相同的种子,并产生相同的结果。

    【讨论】:

    • 谢谢,这解决了问题!
    猜你喜欢
    • 2015-08-16
    • 2015-12-29
    • 2010-12-07
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    相关资源
    最近更新 更多