【发布时间】:2020-06-16 07:58:09
【问题描述】:
我是 C++ 新手,想访问子类中的值。 当我尝试访问这些值时,我的程序崩溃并返回堆栈转储。
例如:
class test{
protected:
std::string name;
int points;
object** inventory;
public:
test(const std::string name, int points) : name(name), points(points), inventory(new object*[10]()) {
for(int i = 0; i < 10; i++) {
this->inventory[i]->setValid(false);
}
}
class object {
protected:
bool isValid;
std::string name;
int value;
public:
object(const std::string name, int value) : name(name), value(value), isValid(false) {}
const std::string getName();
bool getValid();
void setValid(bool isValid);
};
在头文件中:
void object::setValid(bool isValid) {
this->isValid = isValid;
//std::cout << isValid; returning of isValid is possible, but not of this->isValid
}
包括必要的头文件和声明。 在调试时,它会在我的类对象中尝试获取 this->isValid 的值时停止,并显示以下错误消息:
执行 MI 命令失败:
-data-evaluate-expression ((this)->isValid)
来自调试器后端的错误消息:
无法访问地址 0xc 的内存
我是否使用了不正确的指针?我该如何解决这个问题?
【问题讨论】:
-
你的意思是一个子类?您的代码中没有子类
-
很可能,您没有正确初始化您的库存数组,如果有的话
-
最接近的原因是猜测,询问者试图做什么,就像唯一的答案一样。这个问题应该因为不清楚或缺少minimal reproducible example 而被关闭。如果我不认为它会立即重新锁定,希望有更好的理由,我会解锁它。
-
@user 我不同意。他们说他们遇到了 SegFault 并寻求解决方案。他们的程序有 UB,因为他们已经将
inventory初始化为new object*[10](),并且他们试图用this->inventory[i]->setValid(false);取消引用未初始化的指针。我认为骗子完美地解释了他们的 UB,并将帮助他们解决 SegFault。是什么让你说这不清楚? -
@scohe001
this->inventory[i]->setValid(false);不是试图使用二维数组的人的行为。我认为提问者在object** inventory;处添加了一个额外的间接级别。其余部分来自于试图清除编译器错误而没有真正理解为什么会出现编译器错误。加尔的回答可能是正确的想法。目前还不清楚,因为如果没有提问者的更多输入,就无法确定。