变量未在 switch case 语句中定义

variable not defined in a switch case statement

这是我的 switch case 语句。编译器一直声明 totalShare 未定义,即使它在情况 1 中已定义。我是 C++ 的初学者,刚开始学习堆栈。

switch (option)
{
    case 1:
    {
        string newStock;
        double share;
        double price;

        cout << "Enter a new stock: " ;
        cin >> newStock;

        cout << "Enter a number of shares: " ;
        cin >> share;

        cout << "Enter price [for that number of shares]:  " ;
        cin >> price;

        //share x price
        double sharePrice = share * price;

        //add to stack
        newStockStack.push(sharePrice);

        //total share
        double totalShare;
        totalShare += share;
        break;
    }

    case 2:
    {
        //calculate stacks
        double theTotal;
        while (!newStockStack.empty())
        {
            theTotal += newStockStack.top();
            newStockStack.pop();
            return theTotal;
        }
        // FORMULA
        //((every share x price)+ (every share x price)) / total number of shares

        double LifoPrice;
        LifoPrice = (theTotal / totalShare);
        cout << "The Lifo price for the stock is: " << LifoPrice << endl;
        break;
    }

double totalShare; 出现在 "case 1" 块内

这意味着,totalShare 对于该块是本地的,即它的范围仅在情况 1 内,并且在该块之外是不可见的。

但是 "case 2" 块 中有 LifoPrice = (theTotal / totalShare);。这就是为什么您的编译器会抱怨 totalShare 未定义(在 case 2 块内)。

解法:

在这样的范围内定义该变量,以允许您在任何需要的地方使用它。在这种情况下,由于您需要在多个 case 块中使用该变量,请考虑在 switch 语句之外声明该变量。因为限制变量的范围是一种很好的做法,如果您只在 switch 语句中需要该变量,那么您可以在 switch 语句中但在所有需要 totalShare.[=15 的 case 块之前声明它=]

变量 totalShare 在标签 case 1: 下的块范围内声明。

case 1:
{
    //...

    //total share
    double totalShare;
    totalShare += share;
    break;
}

所以在标签case 2:下的块范围内是不可见的

LifoPrice = (theTotal / totalShare);

您可以在任何 case 标签之前声明变量。

或者如果编译器支持 C++ 17 标准,那么您可以在 switch 语句中声明它。