什么是自引用C ++类型有用?

时间:2012-08-24 16:11:57

标签: c++ reference

自引用类型的用例是什么?

通过自我引用类型,我的意思是:

class T { 
  T *ptr; // member variable that references the type of the class
};

2 个答案:

答案 0 :(得分:2)

这是构建链表或树的最有效方法之一 层次结构。

#include <iostream>

class linked_ints {
public:
  linked_ints() : next(nullptr), x(0) {}
  linked_ints* next;
  int x;
};

void print(linked_ints* b) {
  if(b == nullptr) return;
  do {
    std::cout << b->x << std::endl;
  } while((b = b->next));
}

int main()
{
  linked_ints x, y, z;
  x.next = &y; y.next = &z;

  print(&x);

  return 0;
}

答案 1 :(得分:2)

我能想到的一个例子是linked lists

借鉴here

的例子
#include<iostream>
struct Node{
  int data;
  Node* next;
};
void InsertAfter(Node **head, int value){
  if(*head==NULL){
    Node* temp=NULL;
    temp = new Node;
    temp->data = value;
    temp->next = NULL;
    *head = temp;
  }else{
    Node *temp = new Node;
    temp->data = value;
    temp->next = (*head)->next;
    (*head)->next = temp;
  }
}
void DeleteAfter(Node **head){
  if(*head==NULL){
    return;
  }else{
    Node *temp = NULL;
    temp = (*head)->next;
    (*head)->next = (*head)->next->next;
    delete temp;
    temp=NULL;
  }
}
int DeleteAll(Node **head,int value){
  int count=0;
  Node *p = NULL;
  Node *q = (*head);
  if(*head==NULL){
    count =0;
  }else{
    while((q)!=NULL){
      if((q)->data==value){
        Node *temp = NULL;
        temp = q;
        if ( p!=NULL){
          p->next = q->next;
        }else{
          (*head) = q->next;
        }
        q = q->next;
        delete temp;
        temp = NULL;
        ++count;
      }else{
        p = q;
        q = q->next;
      }
    }
  } 
  return count;
}
void DisplayList(Node *head){
  if(head!=NULL){
    std::cout << head->data << "\n";
    while(head->next!=NULL){
      std::cout <<  head->data << "\n";
      head = 
      head->next;
    }

    std::cout << "\n\n";
}
int main(){
  Node *head=NULL;
  InsertAfter(&head,10);
  InsertAfter(&head,10);
  InsertAfter(&head,20);
  InsertAfter(&head,10);
  DisplayList(head);
  DeleteAfter(&head);
  DisplayList(head);
  int a = DeleteAll(&head,10);
  std::cout << "Number Of Nodes deleted 
                having value 10 = " << 
                a <<"\n\n";
  DisplayList(head);
  return 0;
}