't'未在此范围中声明
' t ' was not declared in this scope
大家好,我昨天已经开始学习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在这里找到的书之一。
相关文章:
- 错误:未在此范围内声明'reverse'
- 在基于范围的for循环中使用结构化绑定声明
- 错误:"imread"未在此范围内声明
- 我在范围内未声明的错误类有问题
- 未在此范围内声明错误 'xy'
- Socklen_t未在此范围内声明
- 如何从未知视图中声明范围::v3::View 变量
- 错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明
- "Main"已在当前范围内声明
- c++ 变量在宏的扩展中没有在这个范围内声明
- 朋友声明的复杂范围界定规则有什么意义?
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- 'num1'未在此范围内声明
- 在此范围内未声明错误"Clreol"
- 如何找到在本地范围内声明的变量的地址?
- 简化在 Pybind11 中为 C++ 模板类生成包装类:模板声明不能出现在块范围内
- C++模板专用化中的声明范围
- 这是有效的C++代码吗?(在声明范围之外使用本地类型)
- 函数声明范围
- 如何在类声明范围内使用“using space::function”