例如:
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处的内存
我使用不正确的指针吗?我该如何解决这个问题?
最好的问候,凯塔
object** inventory;
一旦您这样做:
inventory(new object*[10]())
您现在可以通过清单[9]访问清单[0]。但是他们还没有设置任何东西。它们甚至可能不是null,而只是垃圾内存。您可以在循环中分配对象:
for(int i = 0; i < 10; i++) { inventory[i] = new object(); inventory[i]->setValid(false); }
但是,您需要记住要释放所有这些对象。您可能会考虑使用数组分配器来分配对象数组,而不是指向对象的指针数组。但是,因为这是C ++,所以最好使用向量。
std::vector<object> inventory