这是我的骰子.h
class Dice
{
public:
int value;
int nrOfFaces;
Dice();
void toss();
};
这是我的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;
}
稍微解释一下我在这里要做什么。我将在本文底部发布主要代码。在主代码中,我停在了你可以看到的那部分,我声明了一个指针数组。现在,我试图先在一个循环中抛出 5 个骰子。在另一个 foor 循环中,我试图打印出 5 个骰子的值。但是我这样做的方式似乎不起作用。我没有收到错误,但程序在到达 pYatzy[i]->toss();
时中断这是我的 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;
}
谢谢!
最佳答案
这里你创建了 5 个未初始化的指针:
Dice *pYatzy[5];
在这里您取消引用未初始化的指针,这会导致未定义的行为:
for (int i = 0; i < 5; i++)
{
pYatzy[i]->toss();
一个简单的解决方案是将该代码替换为:
Dice pYatzy[5];
for (int i = 0; i < 5; i++)
{
pYatzy[i].toss();
此外,在您的代码的前面,您可以编写 Dice dice1; dice1.toss();
等,而不是使用 new
。在 C++ 中,99% 的时间都不需要使用 new
。
关于c++ - 我无法使用指针数组从 main 访问函数(在类中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28059395/