0

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

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

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

2 回答 2

2

我能想到的一个例子是链表

从这里借来的例子:

#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;
}
于 2012-08-24T16:17:12.983 回答
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;
}
于 2012-08-24T16:13:57.000 回答