在 C++ 中:在函数中初始化变量与在函数标头中声明变量有什么区别?

In c++: what is the difference between initializing a variable in a function versus declaring it in the function header?

本文关键字:变量 函数 区别 什么 声明 C++ 初始化      更新时间:2023-10-16

区别只在于你能用它们做什么吗?

另外,如何将函数中变量的结果传递给另一个函数?最近,我不得不这样做,但变量没有将父函数中的代码传递给另一个函数。

void add(int a, int b)

void add(int a)
int b;
a+b;

以及将变量的结果从父函数传递到函数:

void add(int a, int b, double c)
a+b=c;

void divide(double c, int d, double e)
c / d = e; 

这两个函数之间有很大的区别(我添加了一些缺失的细节)

void add(int a, int b)
{
int c = a + b;
}
void add(int a)
{
int b = 10;
int c = a + b;
}

在第一种情况下,您可以调用传递两个参数的函数。例如

add( 2, 5 );

在函数变量 c 内部将有一个取决于两个参数的值(如果 a = 2,b = 5,则 c = 7)。

在第二种情况下,您可以调用仅传递一个参数的函数

add( 2 );

因此,如果指定为参数 2,那么您将获得 c 将等于 12.您无法更改调用该函数的 b 的值,因为您无法访问它。

考虑到此代码不会被编译

void add(int a, int b, double c)
{
a + b = c;
}

您不能将表达式a + b

如果需要将结果从一个函数传递到另一个函数,则可以将其传递到函数返回对象。对于示例,在第一个函数中将返回类型从void更改为int

int add(int a, int b)
{
int c = a + b;
return c;
}

在这种情况下,您可以将结果传递给"父"函数。例如

#include <iostream>
int add(int a, int b)
{
int c = a + b;
return c;
}
void add(int a, int b, double c)
{
std::cout << a + b + c;
}

int main()
{
int x = 10;
int y = 20;
int z = 30;
add( x, y, add( x, z ) )'
}

输出将等于 70 ( x + y + (x + z ) )。在此示例中,有两个重载函数,名称为 add 其中一个有两个参数,另一个有三个参数。

此外,您还可以使用通过使用指针的引用传递的参数来获取函数结果。

例如

#include <iostream>

void add(int a, int b, double &c)
{
c = a + b;
}

int main()
{
int x = 10;
int y = 20;
int z;
add( x, y, z ) );
std::cout << "z = " << z << std::endl;
}

结果将是 z = 30。

如果使用 poinetrs,则代码将如下所示

#include <iostream>

void add(int a, int b, double *c)
{
*c = a + b;
}

int main()
{
int x = 10;
int y = 20;
int z;
add( x, y, &z ) );
std::cout << "z = " << z << std::endl;
}

结果将与 30 相同。

区别在于变量的范围。在函数体中声明的变量将具有块范围。标头中声明的变量将具有文件范围。

void add(int a, int b, double c)
a+b=c;
void divide(double c, int d, double e)
c / d = e; 

这段代码完全是胡说八道。让我尝试为您修复它:

int add(int a, int b)
{
return a + b;
}
double divide(double c, int d)
{
return c / d;
}

不知道为什么有人会限制d成为int.但是,嘿,我什至看不出添加和划分函数的意义,因为人们可以简单地使用旧的+/来开始:)

如果在标头中声明该函数,则可以在包含该标头的所有源文件中访问该函数。这可以使常量,静态或外置。如果你把它设为extern,不要忘记你还需要在其中一个源文件中定义变量:

// header.h
#pragma once
int a;             //these variables will be usable in all the source files that include this header
static const int b = 5;  //this is a const static variable, you cannot assign a new value to it.
extern int c;  // this is extern, must be defined in a soruce file
int fun(int); // and this is a function taking an int, returning another int

和源文件:

#include "header.h"
int fun(int g)
{
return g + 1;
}
int c = 7;
int main()
{
a = 5;    // assign a value to it
fun(a);   // this is how you use it
}

如果初始化(假设初始化意味着声明)函数中的变量,则只能从该函数访问该变量。

关于"一个函数中的一个变量到另一个函数的结果",你可能想创建一个接受参数的函数。请参阅上面的代码。