c++ - use of & while creating object of structure -


suppose have program

struct node {     int bot,el;     char name[16]; };  int main() {   stack < node > s;   node&b = s.top;   return 0; } 

what & in node&b mean?

first off, should fix call top:

node &b = s.top() ; 

so @ point b alias top element in stack changes make b reflected top element in stack well. taking reference elements in standard container can dangerous , understand implications. code demonstrates principle, while staying close example code possible:

int main() {   std::stack <node> s;    node n1 ;    n1.bot = 10 ;   n1.el  = 11 ;    s.push(n1) ;    node  = s.top() ; // copy of top() , changes won't reflected   node &b = s.top() ; // b alias top() , changes reflected    a.bot = 30 ;   std::cout << s.top().bot << std::endl ;   b.bot = 20 ;   std::cout << s.top().bot << std::endl ;    return 0; } 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -