在函数本身而不是在主函数中声明由参数限定的变量有什么问题?
what is the problem with declaring a variable bounded by a parameter in the function itself rather than in the main function?
我一直试图在函数本身中包含变量的声明,但除非我将其包含在主函数中,否则它不起作用。为什么会这样?
#include<iostream>
using namespace std;
function1(int x)
{
int x =1;
cout << x << endl;
return 0;
}
int main ()
{
function1( x);
return 0;
}` `
欢迎来到C++编码的世界!看起来这里的代码中存在很多问题 - 让我们分解一下,看看我们能找到什么。
首先,为了回答您最初的问题,您对 x(在function1
中(的声明是在您尝试使用变量的函数(在main
中(之外进行的。C++通常看不到你在一个函数中声明的变量,当它在另一个函数中运行时;这是设计使然,称为范围。
首先,由于多种原因,代码无法编译,首先是最后代码中存在杂散反引号。这些需要删除。
int main ()
{
function1( x);
return 0;
}` ` //<-- the ` ` will make the compiler angry
现在让我们看一下导致错误的原因:x 尚未声明。在C++中,变量必须先"声明",然后才能使用。由于"x"在function( x);
中使用之前没有被声明,编译器会把它踢回来,因为它不知道"x"是什么意思。试试这个:
int x = 0;
function1( x);
不过,我们还没有完全完成。一旦我们进行了此更改,编译器将抛出另一个错误:In function 'int function1(int)': 8:5: error: declaration of 'int x' shadows a parameter
.您已经在函数 1 的定义中包含了一个 int x;通过在 function1 中创建另一个int x
,您已经蒸蒸了原始x
。让我们将其从定义更改为赋值。
function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
越来越糟糕,但我们还有一个错误:6:16: error: ISO C++ forbids declaration of 'function1' with no type [-fpermissive]
.这是告诉你function1
需要一个返回类型,这是函数名称前面的关键字,告诉编译器它返回什么类型的数据(如果它不返回任何数据类型void
(。看起来您正在使用return 0;
- 为什么不返回一个 int?
int function1(int x)
现在,我们终于有了可以编译和运行的代码。
#include<iostream>
using namespace std;
int function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
int main ()
{
int x = 0;
function1( x);
return 0;
}
试试这里!
祝你好运!
为什么会这样?
发生这种情况是因为x
现在在main
中使用它的上下文中未定义,并且它已经在您尝试在function1()
中定义的上下文中定义(作为参数(。
在第一种情况下,您肯定会收到错误,因为main
中使用的x
是完全未定义的......编译器将查看该function1(x)
调用,并想知道它应该为x
提供什么。
在后一种情况下,编译器可能会允许您重新定义x
,但它可能至少会发出警告。此外,如果允许,则无论您为x
参数传入什么,您的function1()
都将始终打印出1
,因为将使用新声明的x
而不是参数中传递的值。
您缺少的概念称为范围。每个变量都有一个作用域,它本质上是已知的领域。变量的作用域可以是全局的,在这种情况下,它可用于整个程序,或者仅限于单个文件,或者它可以在函数或块中声明,在这种情况下,它是该代码块的本地。
int x = 12; // x is available anywhere in the file and has initial value 12
void foo(int x)
{
cout << x << endl; // prints the value passed to foo by the caller
int x = 34; // this new x hides the parameter and is available
// anywhere inside this function, but not outside
cout << x << endl; // prints the new x, i.e. 34
{
cout << x << endl; // still prints 34
int x = 97; // hides the previous x, available only within
// this block or sub-blocks
cout << x << endl; // prints 97
} // x from the enclosed block goes out of scope
cout << x << endl; // prints 34, because we're back to the x at function scope
}
了解作用域非常重要,因为变量名称经常是有意或无意重复的,您需要能够分辨给定变量在作用域中的位置,因此可以使用有效,何时无效。
- 未使用的C++未优化的静态成员函数/变量
- 内联函数/变量的外部链接
- 同一函数中的静态函数变量初始化顺序
- 将非静态成员函数C 的使用无效,而将成员功能作为函数变量
- 如何从doxygen输出中排除类的无证件成员函数/变量
- 如何在LUA C API中分配全局LUA函数变量
- 如何将函数变量传递给C lambda函数
- 通过另一个C++函数更改函数变量
- c++11 lambda 真的支持闭包吗?函数变量中存在语义冲突
- C++:静态成员不能在声明时定义,但静态函数变量可以?
- apache-frift是否支持函数变量作为参数
- 类函数/变量在使用之前必须声明
- 函数变量去哪里
- 无法使用函数变量?错误表达式必须具有类类型
- 如何在main中使用函数变量
- 每当尝试打印函数变量时,C++ cout 错误
- 是否存在查看成员函数/变量的整洁等效项
- 访问友元类之间的函数变量
- 函数到函数变量
- 一个定义规则是否强制创建一个静态函数变量