[英]Pointer to table of object
我想在所有Spam方法中使用对象的foo数组。
#include "spam.h"
class Foo: public Bar
{
public:
Foo(Layer* layer)
int getNumber() const;
// Something else
};
class Spam: public Layer
{
Spam();
// some methods
private:
Bar** foo; //here is the problem
};
创建一个对象时,这种方法(当然带有一个*)对我有用。
void Spam::fun1()
{
Bar **foo = new Bar*[1];
foo[0] = new Foo(this);
//foo[1] = new Foo(this);
//foo[1]->getNumber(); // works correctly
}
void Spam::fun2()
{
//foo[1]->getNumber(); // foo[1] and foo[2] are NULL
foo[0]->getNumber(): // not working at all
}
但是,即使我使用Bar ** foo或Bar ** foo [2],Xcode也会告诉我创建了对象的新指针。
[edit]我注释了错误的代码示例,我的疏忽,谢谢大家。
在您的fun1
,语句Bar **foo = new Bar*[1];
定义一个新的局部变量foo
,该变量隐藏类成员名称。
如果要改为引用类成员,请说foo = new Bar*[1];
。
看来您这里有缓冲区溢出:
Bar **foo = new Bar*[1]; // allocate one-element array of pointers to Bar
foo[0] = new Foo(this); // valid assignment
foo[1] = new Foo(this); // off the end of the array.
在Spam :: fun1()方法中,您已将内存分配给类型为“ Bar **”的局部变量“ foo”。 相反,您必须为类成员变量“ foo”分配内存。 您可以做两件事来解决这个问题,
为此,请使用以下代码代替“ Bar ** foo = new Bar * [1];”来删除局部变量声明“ foo”。 在“垃圾邮件:: fun1()”中。
foo = new Bar * [1];
如果由于某些原因要保留局部变量,请使用“ this”指针指示类成员,
this-> foo = new Bar * [1];
只是一个建议,如果您遵循如下所示的源代码中正确的命名约定,则可以避免此类混淆。
class CSpam: public CLayer
{
private:
Bar ** mFoo;
};
void Spam::fun1()
{
mFoo = new Bar*[1];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.