C++访问子类的方法

How to access subclass in C++

我是 C++ 新手,想访问子class 中的值。 当我尝试访问这些值时,我的程序崩溃并返回堆栈转储。

例如:

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
}

包括必要的头文件和声明。 调试时它在我的 class 对象中尝试获取 this->isValid 的值时停止,并出现以下错误消息:

Failed to execute MI command:
-data-evaluate-expression ((this)->isValid)
Error message from debugger back end:
Cannot access memory at address 0xc

我使用的指针不正确吗?我该如何解决这个问题?

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

object** inventory;

执行此操作后:

inventory(new object*[10]())

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

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

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

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

std::vector<object>  inventory