c++ - 返回指针的方法,指向在另一个 header 中声明的数组对象,

标签 c++ arrays pointers methods forward-declaration

我遇到了两个相互交织的问题。

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

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

我当前的代码是一些摸索的结果,并且会失败,因为我不能在没有完全声明的情况下将“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];
}

酒吧.h

#ifndef BAR_H
#define BAR_H

#include <iostream>

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

最佳答案

除了一些拼写错误外,编译正常:

  1. 定义栏类后需要一个分号。
  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

关于c++ - 返回指针的方法,指向在另一个 header 中声明的数组对象,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4405340/

相关文章:

c++ - 在没有管理员权限的情况下获取主域 SID

c++ - VS2008 二进制比 VS2005 慢 3 倍?

c++ - 为什么 insert_or_assign 没有迭代器重载?

C - 调用新函数时的指针

c - C中指向指针和realloc的指针

c++ - 变量如何既是 constexpr 又不是 constexpr?

c++ - C++中使用指针的数组中元素的数量

javascript - 如何将 PHP JSON 转换为 JS 数组

javascript - className null还是不是一个对象

C、如何使用这个树结构