【问题标题】:Method to return pointer, pointing to array object declared in another header,返回指针的方法,指向另一个头文件中声明的数组对象,
【发布时间】:2011-05-23 06:20:42
【问题描述】:

我有点被两个相互交织的问题所困扰。

  • 首先,我想要一个指向堆上对象的指针数组。 (在另一个标头中声明的对象)

  • 其次,我想让一个方法返回一个指向这些对象之一的指针。

我当前的代码是一些摸索的结果,并且会失败,因为我不能在没有完全声明的情况下使用“bar”作为返回类型。但我看不出还有什么办法可以解决这个问题。我试图让“getBar”成为一个指向函数的指针,但是我不知道如何让它访问 **barArray 而不是成员方法。

任何帮助将不胜感激:D

我的代码:

foo.h

#ifndef FOO_H
#define FOO_H

//forward declaration
class bar;

class foo  
{  
    public:  
        //constructor
        foo(int x);  
        //method
        bar * getBar(int y);  
    private:  
        int howManyBars;
        bar **barArray;  
};

#endif

foo.cpp

#include "foo.h"
#include "bar.h"  

//constructor
foo::foo(int x)
{
    howManyBars = x;
    barArray = new bar *[howManyBars];

    for (int i=0; i < howManyBars ; i++)
    {
        barArray[i] = NULL; //set all pointers to NULL
    }
}

//method
bar * foo::getBar(int y)
{
    y = (y - 1);
    // if the pointer is null, make an object and return that
    if (barArray[y] == NULL)
    {
        barArray[y] = new bar();
    }
    return barArray[y];
}

bar.h

#ifndef BAR_H
#define BAR_H

#include <iostream>

class bar
{
    public:
        void test(){std::cout << "I'm alive!\n";};
};
#endif

【问题讨论】:

  • 别忘了在 foo =) 的析构函数中删除你的对象

标签: c++ arrays pointers methods forward-declaration


【解决方案1】:

除了一些错别字之外,这编译得很好:

  1. 定义 bar 类后需要一个分号。
  2. bar * foo:getBar(int y)

应该是:

bar * foo::getBar(int y)

3.

bar[i] = NULL; //set all pointers to NULL

应该是:

barArray[i] = NULL; //set all pointers to NULL

【讨论】:

  • 诅咒我的工作示例!至少这意味着我已经理解了这个概念。当我在另一个应用程序中运行它时,我在 foo.h 中收到“错误:ISO C++ 禁止声明没有类型的 'bar'”标头也在其他地方加载,但我看不出这是一个问题 上的#define 守卫
猜你喜欢
  • 2020-12-11
  • 2017-12-26
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2014-09-09
  • 1970-01-01
相关资源
最近更新 更多