C++变量作用域(详解版)

  • 内容
  • 评论
  • 相关

C++ 允许在程序中几乎任何地方创建变量。常见的做法是在函数顶部定义函数的所有变量,也就是在标记主体开始的开放大括号之后。当然,在一些更长的程序中,变量有时在程序使用它的位置附近定义,只要在使用之前定义它们就没问题。

我们知道,使用大括号包围一个或多个编程语句即定义了一个代码块。函数 main 的主体必须被大括号包围,它就是一个代码块。与 if 或 if-else 语句中的 else 相关联的一组语句也同样是代码块。

无论如何,变量都需要定义在代码块的内部,也可以在任何代码块内定义一个变量。变量的作用域就是它的定义语句和块的闭括号之间的那一部分。因此,在函数顶部定义的变量,其作用域实际上就是整个函数,而内部块中定义的变量,其作用域就是该块。

下面的程序在后面定义了它的变量:

#include <iostream>
using namespace std;

int main()
{
    //Constants for minimum income and years
    const double MIN_INCOME = 35000.0;
    const int MIN_YEARS = 5;
    // Get the annual income
    cout << "What is your annual income? ";
    double income; // Variable definition
    cin >> income;
    if (income >= MIN_INCOME)
    {
        //Income is high enough, so get years at current job
        cout << "How many years have you worked at your current job? ";
        int years; // Variable defined inside the if block
        cin >> years;
        if (years > MIN_YEARS)
            cout << "\nYou qualify.\n";
        else
            cout << "\nYou must have been employed for more than "<< MIN_YEARS << " years to qualify.\n";
    }
    else // Income is too low
    {
        cout << "\nYou must earn at least $" << MIN_INCOME << " to qualify.\n";
    }
    return 0;
}

程序的第 11 行中定义了 income 变量,它在标记 main 函数代码块的大括号内,所以它的作用域包括第 11〜28 行,也就是从它被定义的行到 main 函数封闭大括号的位置,在这个作用域内它都可以被程序使用。

years 变量在第 18 行中定义,包围它的大括号标记的代码块是由 if 语句有条件地执行的代码块,所以它的作用域只包括第 18〜22 行。也就是从它被定义的点到关闭if代码块的大括号之间的行。这些在一组大括号内定义的变量被称为具有局部作用域或块作用域。在局部作用域之外,这些变量是不可见的,也不能被使用。

注意,当一个程序正在运行并且它进入构成一个变量作用域的代码段时,就称该变量进入作用域。这只是意味着变量现在可见,程序可以引用它。同样,当一个变量离开作用域时,它就不再能敢使用。

同名变量

当块嵌套在另一个块中时,内部块中定义的变量可能与外部块中定义的变量具有相同的名称。虽然一般认为这样做不妥,因为它很可能会导致混乱,但其实这样做是被允许的。当内部块中的变量进入作用域时,外部块中的变量变为“隐藏”,不能使用。下面的程序说明了这一点:

// This program uses two variables with the same name.
#include <iostream>
using namespace std;

int main()
{
    int number; // Define a variable named number
    cout << "Enter a number greater than 0: ";
    cin >> number;
    if (number > 0)
    {
        int number; // Define another variable named number
        cout << "Now enter another number: ";
        cin >> number;
        cout << "The second number you entered was ";
        cout << number << endl;
    }
    cout << "Your first number was " << number << endl;
    return 0;
}

程序输出结果:

Enter a number greater than 0: 2
Now enter another number: 7
The second number you entered was 7
Your first number was 2

此程序中有两个单独的变量名 number。一个在外部块中的第 7 行上定义,另一个在内部块中的第 12 行上定义。内部块中的 cin 和 cout 语句(属于 if 语句)只能与该块中定义的 number 变量一起使用。一旦程序离开该块,内部 number 离开作用域,将再次显示外部 number 变量。

警告,尽管在嵌套块中定义变量是完全可以接受的,但是在命名时应该避免与外部块中的变量相同,毕竟这样太容易将一个变量与另一个变量混淆了。

本文标题:C++变量作用域(详解版)

本文地址:https://www.hosteonscn.com/3717.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注