【问题标题】:Pointer to table of object指向对象表的指针
【发布时间】:2017-01-05 02:10:37
【问题描述】:

我想在所有 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 也会显示我创建了指向对象的新指针。

Xcode screenShoot

[编辑]我注释掉了错误的代码示例,我的疏忽,谢谢大家。

【问题讨论】:

  • 您没有以健康的方式使用“正常工作”。显然foo[1] 是越界访问。
  • 您的示例中包含foo[1] 且“正常工作”的任何语句似乎都有效。它可能随时无缘无故停止工作。这是因为 foo 仅包含 1 个元素(因为 `new Bar*[1]'),这意味着只有索引 0 是合法访问的(对于大小为 N 的数组,您可以访问索引 0 到 N-1)。有关未定义行为的更多信息,请参阅this answer。
  • 好吧,我同意,这是我的错,即使是 foo[0],也在 Spam::fun1() 中工作,但我正在寻找正确的方法来指出这一点并在 Spam 中使用相同的对象::fun2(),这是我的问题。

标签: c++ class oop pointers


【解决方案1】:

在您的fun1 中,语句Bar **foo = new Bar*[1]; 定义了一个新的局部变量foo,它隐藏了类成员名称。

如果您想引用班级成员,请说foo = new Bar*[1];。

【讨论】:

    【解决方案2】:

    看起来你这里有缓冲区溢出:

    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.
    

    【讨论】:

      【解决方案3】:

      在 Spam::fun1() 方法中,您将内存分配给“Bar **”类型的局部变量“foo”。相反,您必须为您的类成员变量“foo”分配内存。你可以做两件事来解决这个问题,

      1. 删除“foo”的局部变量声明,使用下面的代码代替“Bar **foo = new Bar*[1];”在“Spam::fun1()”中。

        foo = new Bar*[1];

      2. 如果由于某些原因想保留局部变量,使用“this”指针来指示类成员,

        this->foo = new Bar*[1];

      只是一个建议,如果您在源代码中遵循正确的命名约定,如下所示,您可以避免此类混淆。

      class CSpam: public CLayer
      {
      private:
      Bar ** mFoo;
      };
      
      void Spam::fun1()
      {
        mFoo = new Bar*[1]; 
      }
      

      【讨论】:

      猜你喜欢
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 2014-01-02
      相关资源
      最近更新 更多