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

标签 c++ arrays class pointers object

这是我的骰子.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/

相关文章:

c++ - #include <Windows.h> 是不好的做法吗?

c++ - 在静态函数中返回一个对象而不是构建它有什么好处?

java - 如何将 ASCII 转换为字符串

c++ - 如何在声明时将对象插入到 std::map 中

c++ - 指向 void 函数中的类的指针

C++:从函数更改类成员值

c++ - std::optional:不参与重载决议与被定义为已删除

c++ - 重载 operator<< 以处理字符串

javascript - 将包含 python 列表的字符串转换为 javascript 数组

c - 如何在 C 中正确比较和打印出此数组中的匹配元素?