Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.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++ 我无法使用指针数组从main访问函数(在类中)_C++_Arrays_Class_Pointers_Object - Fatal编程技术网

C++ 我无法使用指针数组从main访问函数(在类中)

C++ 我无法使用指针数组从main访问函数(在类中),c++,arrays,class,pointers,object,C++,Arrays,Class,Pointers,Object,这是我的骰子 class Dice { public: int value; int nrOfFaces; Dice(); void toss(); }; 这是我的骰子 //this is the default constructor (has no parameter) Dice::Dice() { nrOfFaces = 6; value = rand() % nrOfFaces + 1; } //this function gives the dice a new random v

这是我的骰子

class Dice
{
public:
int value;
int nrOfFaces;
Dice();
void toss();
};
这是我的骰子

//this is the default constructor (has no parameter)

Dice::Dice()
{
nrOfFaces = 6;
value = rand() % nrOfFaces + 1;
}

//this function gives the dice a new random value

void Dice::toss()
{
value = rand() % nrOfFaces + 1;

}
来解释一下我想在这里做什么。我将在这篇文章的底部发布主要代码。在主代码中,正如您所看到的,我被困在声明指针数组的部分。现在,我试着在一个foor循环中先掷5个骰子。在另一个foor循环中,我试图打印出5个骰子的值。但是我这样做似乎不起作用。我没有收到错误,但程序在到达pYatzy[I]->toss()时会中断

这是我的主要.cpp

int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

//type cast is done in the c++ way
srand(static_cast<unsigned>(time(NULL)));

Dice *dice1 = new Dice;

cout << dice1->value << endl << endl;

dice1->toss();

cout << dice1->value << endl << endl;


for (int i = 0; i < 5; i++)
{

    dice1->toss();
    cout << dice1->value;
    cout << " ";

}

Dice *pYatzy[5];

for (int i = 0; i < 5; i++)
{

    pYatzy[i]->toss();

}

for (int i = 0; i < 5; i++)
{

}

system("pause>nul");
return 0;
}
intmain()
{
_CRTSETDBG标志(_CRTDBG_ALLOC_MEM_DF|u CRTDBG_LEAK_CHECK_DF);
/c++类型是用C++方式完成的。
srand(static_cast(time(NULL));
骰子*dice1=新骰子;

cout value在这里,您可以创建5个未初始化的指针:

 Dice *pYatzy[5];
在这里,取消对未初始化指针的引用,这会导致未定义的行为:

for (int i = 0; i < 5; i++)
{
    pYatzy[i]->toss();
for(int i=0;i<5;i++)
{
pYatzy[i]->toss();
一个简单的解决方案是将该代码替换为:

Dice pYatzy[5];
for (int i = 0; i < 5; i++)
{
    pYatzy[i].toss();
Dice pYatzy[5];
对于(int i=0;i<5;i++)
{
pYatzy[i].toss();

也可以,在代码中较早的时候,可以编写“代码> DICE DICE1;DICE1.TSOSH”;< /C> >,而不是使用<代码>新< /代码>。C++中不需要使用<代码>新< /代码> 99%。因为老师的指示让我们这么做。你刚才写的代码,还是指针数组吗?我开始用它,因为我知道数组已经是指针了。是吗?@TarikNeaj不,它是一个对象数组。如果你真的想要指针数组,你必须循环调用

new
5次。是的,我首先需要声明一个由5个骰子指针组成的数组。然后我必须扔掉这5个骰子,然后打印出它们的值。你能告诉我怎么做吗?我整晚都在学习和尝试。在你的循环中放入
pYatzy[I]=新建骰子;
。在创建骰子之前,您不能掷骰子。现在我了解了它的工作原理,这就更有意义了。我已经做到了,我想我已经在所有5个骰子中添加了一个随机数(掷骰函数)(我将很快在这里发布代码).但是现在我试图打印出这5个指针的值,但是我没有得到它们的地址,我试着使用*但是不允许我打印出来。我会留下一个代码截图的链接,我试着把它贴在这里,但没有成功-