简体   繁体   English

构造一个内部带有结构的类c ++

[英]constructing a class with a struct inside of it c++

So I have a class which holds a struct inside its private variables and inside this struct I have an array where the size of the array is only determined after the construction of the class. 因此,我有一个在其私有变量中包含一个结构的类,并且在此结构中,我有一个数组,其中数组的大小仅在构造类后确定。

template <typename T> 
class btree {

  public:
    btree(size_t maxNodeElems);
    ~btree() {}

  private:
    // The details of your implementation go here
    size_t maxNodeElems;
    struct node {

      list <T> elements;
      node lvl[];

    };

};

Firstly, do I have to make it so its node * lvl and how do I call the variables inside this struct? 首先,我是否必须使其node * lvl以及如何在此结构内调用变量? Is it the same as a private variable, so whenever I use it inside one of the functions in btree class I can call it be btree.lvl or is it btree->node->lvl or is there a special way to do this? 它是否与私有变量相同,所以每当我在btree class一个函数中使用它时,我都可以将其btree.lvlbtree->node->lvl还是有一种特殊的方法来实现?

Also, my array has to be of maxNodeElems+1 if someone can help me, that'd be much appreciated! 另外,如果有人可以帮助我,我的数组必须为maxNodeElems+1 ,将不胜感激!

You are just declaring the type, not an actual object of that type. 您只是在声明类型,而不是该类型的实际对象。 You need to make your struct declaration public and the object private: 您需要将结构声明设为公共,将对象设为私有:

template <typename T> 
class btree {

  public:
    btree(size_t maxNodeElems);
    ~btree() {}

    struct node {   // <- this is just a declaration of a private inner-class
      list <T> elements;
      node lvl[];
    };

  private:
    size_t maxNodeElems;
    node*  memberNode;   // <- this is the actual private member

};

You can create objects of that type from outside: 您可以从外部创建该类型的对象:

btree<A>::node* n = new btree<A>::node;

For accessing members, you can have public getters & setters in your btree class: 对于访问成员,您可以在btree类中使用公共获取器和设置器:

class btree {
public:
   node* getNode()
   {
      return memberNode;
   }
   //...........
   //...........
};

EDIT: 编辑:

The following works for me (initializing the member): 以下对我有用(初始化成员):

template <typename T> 
class btree {

  public:
    btree()
    {
       memberNode = new btree<T>::node;
    }
    ~btree() {}

    void init()
    {
       memberNode->lvl = new node[10];
    }

    struct node {   // <- this is just a declaration of a private inner-class
      list <T> elements;
      node* lvl;
    };

  private:
    size_t maxNodeElems;
    node*  memberNode;   // <- this is the actual private member

};

int _tmain(int argc, _TCHAR* argv[])
{
   btree<char> b;
   b.init();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM