在循环构造函数调用中创建的对象的副本

duplicates of objects created in looped constructor call

本文关键字:创建 对象 副本 函数调用 循环      更新时间:2023-10-16

我定义了一个类,然后在数组中用构造函数创建它的实例。出于某种原因,这只会创建实例,尽管所有实例都是随机的,但其中许多实例最终都具有完全相同的属性。这是构造函数。

class fNNGA: public fNN
{
public:
    fNNGA()
    {
    }
    fNNGA(int n)
    {
        int i;
        _node.resize(n);
        for(i = 0; i < n; i++)
        {
            _node[i]._activation = -1;
        }
    }
    fNNGA(int n, int inp, int out, int edge)
    {
        int i,u,v;
        _node.resize(n);
        for(i = 0; i < n; i++)
        {
            _node[i]._activation = 1;
        }
        for(i = 0; i < inp; i++)
        {
            setInput(i);
        }
        for(i = n - out; i < n; i++)
        {
            setOutput(i);
        }
        for(i = 0; i < edge; i++)
        {
            v = rand() % (n - inp) + inp;
            u = rand() % v;
            setEdge(u,v);
        }
        init();
    }
};

以下是我尝试创建阵列的一些方法:

fNNGA pop[SIZE];
int main()
{
    for(int i = 0; i < SIZE; i++)
    {
        pop[i] = fNNGA(100,16,8,800);
    }
}

fNNGA *pop[SIZE];
int main()
{
    for(int i = 0; i < SIZE; i++)
    {
        pop[i] = new fNNGA(100,16,8,800);
    }
}

fNNGA *pop = new fNNGA[SIZE];
int main()
{
    for(int i = 0; i < SIZE; i++)
    {
        new(pop[i]) fNNGA(100,16,8,800);
    }
}

如何正确创建这些对象?

不要在构造函数中调用srand。请记住,在大多数平台上,time函数以为单位返回时间,因此,如果您的构造函数在一秒内被调用多次(很可能发生),那么所有这些调用都将调用srand并设置完全相同的种子。

仅在程序开始时调用srand一次。或者使用C++11中引入的新的伪随机数生成类。

首先,如果程序在一秒钟内运行,则不能使用srand,因为time(null)的所有结果都是相同的。此外,每次rand()使用相同的种子进行播种时,它都必须产生相同的值序列。

我的测试代码和输出如下:

#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
#define null 0
int main(int argc, char const *argv[])
{
  srand(time(null));
  cout << "time:" << time(null) << endl;
  cout << "rand 0:" << rand() << " " << rand() << " " << rand() << endl << endl;
  //to make the program run for more than a second
  for (int i = 0; i < 100000000; ++i)
  {
    int t = 0;
    t = t / 3;
    t = t / 3;
    t = t / 3;
    t = t / 3;
    t = t / 3;
    t = t / 3;
    t = t / 3;
  }
  srand(time(null));
  cout << "time:" << time(null) << endl;
  cout << "rand 1:" << rand() << " " << rand() << " " << rand() << endl << endl;
  srand(time(null));
  cout << "time:" << time(null) << endl;
  cout << "rand 2:" << rand() << " " << rand() << " " << rand() << endl;
  return 0;
}

输出:

时间:1452309501

兰特0:5552 28070 20827

时间:1452309502

兰特1:23416 6051 20830

时间:1452309502

兰特2:23416 6051 20830

更多详细信息,参考srand,时间