't'未在此范围中声明

' t ' was not declared in this scope

本文关键字:声明 范围      更新时间:2023-10-16

大家好,我昨天已经开始学习c++了。

我想创建依赖于从文件中读取的值的对象。然而,据说值t没有在范围内声明:

此外,如果我编写代码的方式不一定是最佳实践,我也能理解。作为一个通用的编码概念,我想知道如何预先初始化t,因为我正在创建的对象取决于给定的值

这是代码:

 while(getline(linestream,value,',')){
            if(i==0){
                cout<< "Type " << value << endl;
                type = value;
            }
            else if(i==1){
                cout<< "Code " << value << endl;
                code = value;
            }
            else if (i==2){
                cout << "Count " << value << endl;
                count = atoi(value.c_str());
            }
            else if (i ==3){
                cout << "Price " << value << endl;
                price = atoi(value.c_str());
            }
            else if(i ==4){
                cout << "Other " << value << endl;
                other = value;
            }
            i++;
            if(i ==5){
                if(type == "transistor"){
                    Transistor *t = new Transistor(code,count,price,other);
                }else if (type == "IC"){
                    IC *t = new IC(code,count,price,other);
                }else if (type == "resistor"){
                    Resistor *t = new Resistor(code,count,price,other);
                }else if (type == "capacitor"){
                    Capacitor *t = new Capacitor(code,count,price,other);
                }else{
                    Diode *t = new Diode(code,count,price,other);
                }
                if(counter ==0){
                    LinkedList list(t);
                }else{
                    list.tailAppend(t);
                }
            }
        }

此外,我为其创建潜在对象的所有类都是从基类StockItem 派生的

t不在您可以使用的范围内。您在if语句之后的块中声明了它。相反,您应该在代码块之前将其声明为基类,并在每个if语句之后将其初始化为子类(实际上应该使用switch,但这不是代码评审)

在C++中,所有循环和if子句都有自己的作用域。因此,您应该在if子句之外声明t,并且应该在循环外部声明list。此外,C++是具有严格变量类型的语言,因此您不能更改t的类型,也不能将不同类型的值推送到列表中。要做到这一点,您应该使用没有类型的指针void*,或者创建一个父类,并从该类派生用于t的所有不同类型(在这种情况下,您可以为t使用指向基类的指针)。如果你不知道如何做到这一点,你最好读一些关于C++中面向对象编程的书,这是一个太大的主题,无法在这个答案中解释。

关于这个主题的好书可能是Bjarne Stroustrup在这里找到的书之一。