简体   繁体   中英

Using pointer and reference as return type in same function

So I was looking at some code and I came across this.

class Data{
 private:
  int data;
  Data* next;
 public:
   Data(int d=0): data(d), next(NULL) {}
   void SetData(int d) { data = d;}
   int  GetData() { return data; }
   Data*& GetNext() { return next; }
 }

The GetNext() return type is both the reference and pointer as return type. What does this mean?

X * is a pointer to a X .

T & is a reference to a T . If T happens to be a pointer type, then it is a reference to a pointer: X* & is a reference to a X* .

As such, Data*& is a reference to a pointer to a Data .

The value returned from GetNext() is a reference to a pointer to Data . This means it acts just like a pointer but if you change the value it will change the original object.

int main()
{
     Data*   d1 = new Data(1);
     std::cout << d1->GetData() << " : " << d1->GetNext()   // prints null;
               << "\n";

     d1->getNext() = new Data(2);   // Modify the value.

     std::cout << d1->GetData() << " : " << d1->GetNext()   // Does not print null
               << " -> " 
               <<  d1->GetNext()->GetData() << " : " << d1->GetNext()->GetNext()
               << "\n";
}

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