简体   繁体   English

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

[英]Im not able to access a function (which is in a class) from main, using an array of pointers

This is my dice.h 这是我的骰子

class Dice
{
public:
int value;
int nrOfFaces;
Dice();
void toss();
};

this is my dice.cpp 这是我的dice.cpp

//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;

}

To explain a bit on what Im trying to do here. 稍微解释一下我想在这里做什么。 I'll post the code which is in the main at the bottom of this post. 我将在这篇文章的底部发布代码。 In the main code, Im stuck at the part where, as you can see, I declare an array of pointers. 在主代码中,Im停留在如您所见的声明指针数组的部分。 Now, Im trying to first toss the 5 dices in one foor loop. 现在,我试图先将5个骰子扔进一个底环。 and in the other foor loop Im trying to print out the 5 dice's value. 在另一个循环中,我试图打印出5个骰子的值。 But the way Im doing that doesnt seem to work. 但是我这样做的方法似乎不起作用。 I dont get error but the program breaks when it gets to pYatzy[i]->toss(); 我没有收到错误,但程序在进入pYatzy [i]-> toss()时中断了;

Here is my main.cpp 这是我的main.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;
}

Thank you! 谢谢!

Here you make 5 uninitialized pointers: 在这里,您将创建5个未初始化的指针:

 Dice *pYatzy[5];

and here you dereference the uninitialized pointers, which causes undefined behaviour: 并且在这里您取消引用未初始化的指针,这会导致未定义的行为:

for (int i = 0; i < 5; i++)
{
    pYatzy[i]->toss();

A simple solution would be to replace that code with: 一个简单的解决方案是将代码替换为:

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

Also, earlier on in your code you could write Dice dice1; dice1.toss(); 另外,在代码的前面,您可以编写Dice dice1; dice1.toss(); Dice dice1; dice1.toss(); etc., instead of using new . 等,而不是使用new There is no need to use new 99% of the time in C++ . 在C ++中,不需要使用new 99%的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM