在struct定义之前,C ++类中的Struct返回函数

时间:2013-06-29 02:16:36

标签: c++ class oop object struct

我的C ++程序中有一个名为SuperTree的树结构类,我希望它有一个返回structpair的实例方法,其中一个属性是指向SuperTree对象的指针。

我的insert类中的SuperTree函数应该返回一个Res结构,其中包含对另一个SuperTree对象的引用和一个布尔值。但是,如果我尝试编译代码,我会收到以下错误消息:

supertree.cpp:24: error: ISO C++ forbids declaration of ‘Res’ with no type

我也无法在Res类之前定义SuperTree结构,因为它也不会编译。也许这是C ++泛型类型的一些情况(我还不知道如何使用)。

所以这是我的尝试:

#include <cstdio>
#include <utility>
using namespace std;

class AVL {
public:
    int key;
    int bf;
    AVL* leftChild;
    AVL* rightChild;

    AVL()
    {
    }

    ~AVL() {};

    AVL rotateLeft();
    AVL rotateRight();

    Res* insert(int value);

    int remove();
    int size();
};

// typedef pair<AVL, bool> result;

typedef struct result {
  struct AVL *avl;
  bool changed;
} Res;

请注意,pair定义已被注释掉,但我们也可以为他们回答,我会很高兴!

就是这样,我怎样才能在SuperTree类中同时拥有Res类和Res结构以及SuperTree指针返回函数?

欢迎任何帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

如果两个类或结构必须相互引用,则需要为其中一个或另一个添加前向声明,如下所示:

struct Res; // No typedef is necessary in C++
class AVL {
    ...
    Res* insert(int value);
};
struct Res {
    AVL *avl;
    bool changed;
};

请注意pair<AVL*,bool>也可以使用Res而不是class AVL { ... std::pair<AVL*,bool> insert(int value); }; ,让您跳过前瞻声明:

{{1}}

答案 1 :(得分:2)

因为在定义时两个类都不需要知道另一个类的大小,所以可以使用前向声明

  1. 您可以先声明AVL

    class AVL;  // forward declaration
    
    typedef struct result {
      // Type size information not necessary at declaration time
      // for pointer and reference members,
      // so a forward declaration is enough at this point.
      struct AVL *avl;
      bool changed;
    } Res;
    
    class AVL {
    public:
    ...
        Res* insert(int value);
    };
    
  2. 或首先声明Res

    struct Res;  // forward declaration
    
    class AVL {
    public:
    ...
        // Type size information is not necessary for return values
        // at function declaration time, so a forward declaration
        // is enough at this point.
        // Note: you can even return by value here.
        Res* insert(int value);
    };
    
    struct Res {
      struct AVL *avl;
      bool changed;
    };
    
  3. 请注意,您不必像在C中那样在C ++中键入构造结构,因为您可以使用不带“struct”关键字的类型名称,因此struct Res {...}typedef struct result {...} Res应该相同,除非你无法向后宣告后者。