Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在c++;?_C++_Constructor - Fatal编程技术网

C++ 如何在c++;?

C++ 如何在c++;?,c++,constructor,C++,Constructor,在我在学校的一节课上,我的部分作业包括创建一个构造函数,将随机值分配到二维数组中。虽然我已经能够创建数组,让构造函数将随机值分配到所述数组中,但我似乎无法创建具有不同2D数组的多个对象。我创建的任何对象似乎都具有以前指定给第一个对象的相同值。我在C++方面是相当新的,所以我认为答案几乎没有在我脑海中浮现。短暂性脑缺血发作 #include <ctime> #include <cstdlib> #include <iostream> using namespa

在我在学校的一节课上,我的部分作业包括创建一个构造函数,将随机值分配到二维数组中。虽然我已经能够创建数组,让构造函数将随机值分配到所述数组中,但我似乎无法创建具有不同2D数组的多个对象。我创建的任何对象似乎都具有以前指定给第一个对象的相同值。我在C++方面是相当新的,所以我认为答案几乎没有在我脑海中浮现。短暂性脑缺血发作

#include <ctime>
#include <cstdlib>
#include <iostream>

using namespace std;

const int sizeOfArray = 3;
int myArray;//a

class Matrix
{
public:
  int myArray[sizeOfArray][sizeOfArray];//a
  Matrix ()//b
  {
    srand(time(NULL));
    for(int i = 0; i < sizeOfArray; i++){
      for(int j = 0; j < sizeOfArray; j++){
      myArray[i][j] = rand() % 10;
      }
    }
  }

  void printMyArray();

};
void Matrix::printMyArray()//c
{
  cout<<"The Matrix is as follows: \n"<<endl;
  cout<<myArray[0][0]<<"\t"<<myArray[0][1]<<"\t"<<myArray[0][2]<<"\n"<<endl;
  cout<<myArray[1][0]<<"\t"<<myArray[1][1]<<"\t"<<myArray[1][2]<<"\n"<<endl;
  cout<<myArray[2][0]<<"\t"<<myArray[2][1]<<"\t"<<myArray[2][2]<<"\n"<<endl;
}

int main()
{
  Matrix matrix;
  matrix.printMyArray();

  Matrix natrix;
  natrix.printMyArray();

  return 0;
}
#包括
#包括
#包括
使用名称空间std;
常数int sizeOfArray=3;
int-myArray//A.
类矩阵
{
公众:
int myArray[sizeOfArray][sizeOfArray];//a
矩阵()//b
{
srand(时间(空));
对于(int i=0;icout您正在使用相同的值对随机数生成器进行种子设定,从而重新启动相同的数字序列

time()

为了证明这一点,在对象创建之间添加一个
sleep(2)
,然后您将得到一个不同的RNG种子


要一劳永逸地解决它:不要在类中播种RNG,在main()的开头做一次

无关,但是为什么在全局范围内有一个<代码> int MyLoad;< /C>?C++程序员有很多随机数生成选项,而不是<代码> Rand < /Cord>。考虑使用,如果你想要一些咯咯笑,没有理由我不知道如何编码HAHA。我相信我把它放在那里测试一些。几天前,当我开始这部分作业时,我做了一件事。不过,谢谢你的关注!非常感谢你,这让一切都更清楚了!