gpt4 book ai didi

c++ - 指向基类的指针在 while 循环中丢失,导致段错误。 C++

转载 作者:行者123 更新时间:2023-11-30 01:17:45 25 4
gpt4 key购买 nike

此代码使用 while 循环来获取用户输入并执行适当的命令 - 为了简洁起见,我将其减少为 2 个命令。
Oblock 对象已正确创建(命令“O”),指向基类的指针也是如此。似乎对这两个对象的调用也能正常工作。然而,在返回到 while 循环后,指向对象的指针似乎丢失了,并且尝试访问其成员(命令“t”)会导致段错误。我在下面包含了示例代码 - 我的问题在后面。

#include<vector>
#include<iostream>
#include<string.h>

using namespace std;

class Tetramino {
private:
int squareSize;
vector<string> myShape;
public:
void setValues(int size) {
squareSize = size;
myShape = vector<string> ((size*size), ".");
}
string getValues(int i) {
return myShape[i];
}
int getSize() {
return squareSize;
}
};

class Oblock : public Tetramino {
public:
Oblock() {
setValues(2);
}
};

main () {
string input;
bool runProgram = true;
Tetramino *pBlock;

while (runProgram) {
cin >> input;
if (input == "O")
{
Oblock myBlock;
cerr << "0thi: " << myBlock.getValues(0) << endl;
Tetramino *pBlock = &myBlock;
cerr << "0thi: " << pBlock->getValues(0) << endl;
}
if (input == "t")
{
cerr << "0thi: " << pBlock->getValues(0) << endl;
}
}
return 0;
}
  • 是否在退出 if 语句时解构对象?
  • 是否有更好的方法来重复获取用户输入?

提前感谢您的任何建议!我搜索了与此类似的问题,但找不到适合我需求的问题。

最佳答案

Tetramino *pBlock 在其范围内是局部的。您正在用 if 中的那个覆盖 main 中的那个。

另外,myBlock 是本地的并且会被破坏——你会有一个悬空指针。你应该分配 new (和 delete...)

当你处理“O”输入(并处理delete pBlock 上一个)。

关于c++ - 指向基类的指针在 while 循环中丢失,导致段错误。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23707768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com