结构和函数返回值

Structures and Function return values

本文关键字:返回值 函数 结构      更新时间:2023-10-16

我刚开始做结构,和他们玩了一会儿,然后被烧伤了!

这是第一次展览:

#include <iostream>
 using namespace std;
struct structure1{
  int h;
  int m;
  int s;
 } structVar;
 int func(structure1 x);
  int main(){
structure1 x;
      structVar.h=4;
      structVar.m=6;
      structVar.s=7;
      func(structVar);
     cout<<x.h<<x.m<<x.s<<endl;
        }
  int func(structure1 x){
    --x.h;
    --x.m;
    --x.s;
  };

其输出为:

1072276636-21953788778

但我期望:

356 

所以我尝试了这种方式,展览2:

#include <iostream>
 using namespace std;
struct structure1{
  int h;
  int m;
  int s;
 } structVar;
  struct returnstruct{
  int val1;
  int val2;
  int val3;
  }returnvalue;
 int func(structure1 x);
  int main(){
      structVar.h=4;
      structVar.m=6;
      structVar.s=7;
    func(structVar);
     cout<<returnvalue.val1<<returnvalue.val2<<returnvalue.val3<<endl;
        }
  int func(structure1 x){
    returnvalue.val1=--x.h;
    returnvalue.val2=--x.m;
    returnvalue.val3=--x.s;

  };

并得到了我所需的输出:

356

问题是我无法解释为什么

这种混淆主要是由于变量作用域造成的。

要点:

  • 函数参数名称(如 x)是函数的本地名称。 如果与全局范围的变量存在名称冲突,则局部函数参数将优先。
  • 结构是按值传递的,这意味着创建副本并将其作为参数传递给函数。

案例 1,您有一个名为 structure1 的结构的结构定义。 在此全局范围内,您还有一个名为 structVar 的实例。 然后在 main 函数的作用域内,您定义了一个名为 xstructure1 类型的局部变量。 以下行

  structVar.h=4;
  structVar.m=6;
  structVar.s=7;

正在修改全局作用域变量 structvar 。 然后你打电话

func(structVar);

此行修改全局变量的副本,structVar将其作为函数参数传递给 funcfunc使用名称,x用于引用structure1,但请记住,由于结构是按值传递的,因此此名称是指您在括号之间传递给它的任何结构的副本 - func(structVar) 。 此参数名称 xmain 中定义的其他x没有关系。 它特定于函数的主体或作用域为函数主体,func

你可以通过将函数参数的名称更改为 y 来稍微探索一下,并首先注意到它不会编译,抱怨 x 未定义。 这意味着在该函数的主体中,它不知道您在main中定义的x,因为x是本地的,也称为范围仅为main。 将其与 structVar 进行对比,后者在任何函数的参数列表或主体之外定义。 structVar可以在任一函数中引用,因为它的作用域是全局的。

cout<<x.h<<x.m<<x.s<<endl;

使用这种对作用域的理解,这条线可以看作是在main中定义的x上运行,该没有初始化其成员(h,m,s)或分配任何值,因此是"奇怪"的输出。

现在,让我们看一下您发布的第二个代码块。

在这里,您添加了另一个全局作用域结构,称为 returnvalue 。 现在,您有两个全局范围变量,structVarreturnvalue 。 由于该作用域,structVarmain 中可见,您可以在其中修改其成员值 (h,m,s)。

接下来,将该全局变量传递给 func 作为其参数 x 。 请记住,这是制作structVar的副本,func称之为x。 因此,x的值为 structVar 的 h、m 和 s。

func内部,由于该全局范围,它可以看到returnValue。 使用 structVar 的副本,现在再次称为 x ,您将 returnvalue 的值设置为参数 x 的(前)递减 (--) 值。 由于xstructVar的副本,并且structVar将其成员设置为数字h=4,m=6,s=7,returnvalue然后接收h=3,m=5,s=6。 然后func返回到main

现在,回到main,由于returnvalue是全局范围,main可以看到它并使用cout打印出其值,因此输出356

structure1 x 的值按值传递。这意味着 func 函数将获取调用方永远不会看到的参数的副本。因此,除非func返回某些内容,否则在这种情况下不会有任何效果。

您可以通过引用返回传递x的修改结构,例如 structure1& x 。在后一种情况下,x 是指调用函数的对象。

#include <iostream>
 using namespace std;
struct structure1{    
  int h;
  int m;
  int s;
 } structVar;         
 int func(structure1 x);
  int main(){
structure1 x;      

      structVar.h=4;  
      structVar.m=6;
      structVar.s=7;
      func(structVar); 

我更改了下面的行

     cout<<structVar.h<<structVar.m<<structVar.s<<endl;
        }

我也更改了下面的功能

  int func(structure1 x){  
    --structVar.h;
    --structVar.m;
    --structVar.s;

  };

输出为预期 356