【问题标题】:How to access subclass in C++ [duplicate]如何在 C++ 中访问子类 [重复]
【发布时间】: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-&gt;inventory[i]-&gt;setValid(false); 取消引用未初始化的指针。我认为骗子完美地解释了他们的 UB,并将帮助他们解决 SegFault。是什么让你说这不清楚?
  • @scohe001 this-&gt;inventory[i]-&gt;setValid(false); 不是试图使用二维数组的人的行为。我认为提问者在object** inventory; 处添加了一个额外的间接级别。其余部分来自于试图清除编译器错误而没有真正理解为什么会出现编译器错误。加尔的回答可能是正确的想法。目前还不清楚,因为如果没有提问者的更多输入,就无法确定。

标签: c++ class subclass


【解决方案1】:

这是一个指向对象指针的指针。您分配了一个指向对象的指针数组,但没有分配对象本身。

object** inventory;

一旦你这样做:

inventory(new object*[10]())

您现在可以通过库存[9] 访问库存[0]。但他们还没有设置任何东西。它们甚至可能不是空的,它只是垃圾内存。

你可以在循环中分配对象:

for(int i = 0; i < 10; i++) {
    inventory[i] = new object();
    inventory[i]->setValid(false); 
}

但是,您需要记住释放所有这些对象。您可能会考虑使用数组分配器来分配对象数组而不是指向对象的指针数组。不过既然是C++,最好用vector。

std::vector<object>  inventory

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多