简体   繁体   中英

using a data type declared inside a class outside

I am new to c++ so here is verry silly question for few of you.

class DList {
  public:
    struct DNode {
      int data;
      DNode* next;
      DNode* prev;
      DNode(DNode* ptr1, DNode* ptr2, int val)
      {
        next = ptr1;
        prev = ptr2;
        data = val;
      }
      ~DNode() {}
      public:
      DNode* getNext() {return next;}
      int getNodeVal() {return data;}
    };

This is the DList structure for me.suppose i want to use datatype DNode outside this class in some other cpp file to declare data of DNode type.how can i use it.

It's just a matter of name qualification:

DList::Dnode x;

This also works for externally referring to any variables or functions declared statically within the class.

class DList {
  public:
    struct DNode {
      int data;
      DNode* next;
      DNode* prev;
      DNode(DNode* ptr1, DNode* ptr2, int val)
      {
        next = ptr1;
        prev = ptr2;
        data = val;
      }
      ~DNode() {}
      public:
      DNode* getNext() {return next;}
      int getNodeVal() {return data;}
    };
    static int counter;
    static int f() {/**/} //do some stateless operation related to the class
};
//...
DList::counter++;
int result = DList::f();

You can declare a variable of that type with:

DList::DNode myNode;

If you are in some other cpp file, make sure you #include "DList.h" or whatever the name of that (hopefully) header file is. If it isn't a header file, you should move it to one and possibly consider moving the implementation details to a .cpp file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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