C++ 使用&;在创建结构对象时

C++ 使用&;在创建结构对象时,c++,object,structure,C++,Object,Structure,假设我有一个程序 struct node { int bot,el; char name[16]; }; int main() { stack < node > S; node&b = S.top; return 0; } struct节点 { int bot,el; 字符名[16]; }; int main() { 堆栈S; 节点&b=S.top; 返回0; } 节点&b中的和是什么意思?首先,您应该修复对顶部的调用: node &

假设我有一个程序

struct node
{
    int bot,el;
    char name[16];
};

int main()
{
  stack < node > S;
  node&b = S.top;
  return 0;
}
struct节点
{
int bot,el;
字符名[16];
};
int main()
{
堆栈S;
节点&b=S.top;
返回0;
}

节点&b
中的
是什么意思?

首先,您应该修复对
顶部的调用:

node &b = S.top() ;
因此,此时
b
现在是堆栈中顶部元素的别名,因此对
b
所做的任何更改也将反映在堆栈中的顶部元素上。引用一个标准容器中的元素可能是错误的,因此您可以理解其含义。此代码演示了原则,同时尽可能接近示例代码:

int main()
{
  std::stack <node> S;

  node n1 ;

  n1.bot = 10 ;
  n1.el  = 11 ;

  S.push(n1) ;

  node a  = S.top() ; // a is a copy of top() and changes to a won't be reflected
  node &b = S.top() ; // b is now an alias to top() and changes will be reflected

  a.bot = 30 ;
  std::cout << S.top().bot << std::endl ;
  b.bot = 20 ;
  std::cout << S.top().bot << std::endl ;

  return 0;
}
intmain()
{
std::堆栈S;
节点n1;
n1.bot=10;
n1.el=11;
S.push(n1);
节点a=S.top();//a是top()的副本,对a的更改不会被反映出来
node&b=S.top();//b现在是top()的别名,更改将被反映出来
a、 bot=30;

std::cout首先,您应该修复对
top
的调用:

node &b = S.top() ;
因此,此时,
b
现在是堆栈中顶部元素的别名,因此您对
b
所做的任何更改也将反映在堆栈中的顶部元素上。引用标准容器中的元素可以是,因此您可以理解其含义。此代码演示了原则,同时尽可能接近您的示例代码如下所示:

int main()
{
  std::stack <node> S;

  node n1 ;

  n1.bot = 10 ;
  n1.el  = 11 ;

  S.push(n1) ;

  node a  = S.top() ; // a is a copy of top() and changes to a won't be reflected
  node &b = S.top() ; // b is now an alias to top() and changes will be reflected

  a.bot = 30 ;
  std::cout << S.top().bot << std::endl ;
  b.bot = 20 ;
  std::cout << S.top().bot << std::endl ;

  return 0;
}
intmain()
{
std::堆栈S;
节点n1;
n1.bot=10;
n1.el=11;
S.push(n1);
节点a=S.top();//a是top()的副本,对a的更改不会被反映出来
node&b=S.top();//b现在是top()的别名,更改将被反映出来
a、 bot=30;
std::cout它的意思是
b
node
类型。它的意思是
b
node
类型。。