简单的类构造函数初始化错误
Simple class constructor initialization errors
在
下面的代码片段中使用占位符名称,有人可以解释为什么我总是得到一个C2065(苹果未声明的标识符)和C2228(.weight/.color/.price的左侧)必须有类/结构/联合吗?当然,如果变量与声明匹配,它应该继续通过 while 循环而不会出现任何问题。
int variable = (algorithm that creates a number);
if (variable == certain number)
{
fruitbag1 apple(40,50);
}
else if (variable == another certain number)
{
fruitbag2 apple(25,50);
}
else if (variable == another certain number)
{
fruitbag3 apple(30,50);
}
while (condition)
{
while (another condition)
{
apple.weight();
apple.colour();
}
apple.price();
}
我尝试这样做以试图缓解问题,但无济于事,但出现相同的错误:
int variable = (algorithm that creates a number);
if (variable == certain number)
{
fruitbag1 apple(40,50);
}
else if (variable == another certain number)
{
fruitbag2 apple(25,50);
}
else if (variable == another certain number)
{
fruitbag3 apple(30,50);
}
if (variable is within the range of the certain numbers)
{
while (condition)
{
while (another condition)
{
apple.weight();
apple.colour();
}
apple.price();
}
}
找到的解决方案:
时间较长且效率低下,但效果很好
int variable = (algorithm that creates a number);
if (variable == certain number)
{
fruitbag1 apple(40,50);
while (condition)
{
while (another condition)
{
apple.weight();
apple.colour();
}
apple.price();
}
}
if (variable == another certain number)
{
fruitbag2 apple(25,50);
while (condition)
{
while (another condition)
{
apple.weight();
apple.colour();
}
apple.price();
}
}
if (variable == another certain number)
{
fruitbag3 apple(30,50);
while (condition)
{
while (another condition)
{
apple.weight();
apple.colour();
}
apple.price();
}
}
找不到
apple
-class。
确保主文件中#include "apple.h"
或类似内容。否则,找不到apple
类。如果它在同一文件中定义,请确保它是在使用 apple
的函数的正上方定义的。
我不完全明白这里发生了什么。但请注意,apple
实例在whiles
大括号中是未知的。
这可能会回答C2065 (apple undeclared identifier)
.
如果你修复它,它也可能解决另一个。
例如,您可以执行以下操作:
int variable = (algorithm that creates a number);
...
fruitbag1 *apple = new fruitbag1;
...
if (variable == certain number)
{
*apple = apple(40,50);
}
...
while (condition)
{
while (another condition)
{
apple.weight();
apple.colour();
}
apple.price();
}
所以现在在大括号中是众所周知的...
它被称为scoping
。尝试搜索c++ scope
。
问题是每个 if-else 语句都有自己的块作用域。所以在 if or else 的复合语句中定义的任何变量都是局部变量,并且在控件传递到相应的 if 或 else 复合语句之外后将被销毁。
所以在这个代码片段之后
if (variable == certain number)
{
fruitbag1 apple(40,50);
}
else if (variable == another certain number)
{
fruitbag2 apple(25,50);
}
else if (variable == another certain number)
{
fruitbag3 apple(30,50);
}
这里的名字苹果是未知的。
相关文章:
- 使用默认构造函数引用成员变量初始化错误
- 交换机案例语句中的初始化错误
- 英特尔 MKL 稀疏 QR 求解 C++ 返回未初始化错误
- 在模板类中使用"this"会导致参数初始化错误
- 映射的映射集的映射初始化错误
- C++图形初始化错误(语法或丢失文件缺陷?
- QSQLDATABASE:SIGSEV初始化错误
- 映射的 std::for_each() 给出无效的初始化错误
- 初始化错误过多
- C++初始化错误 std::set
- 简单的类构造函数初始化错误
- 组合框初始化错误:无法读取未定义的属性'constructor'
- OpenCV卡尔曼滤波器初始化错误
- C++11动态数组部分列表初始化(错误或误解)
- C++ 静态变量在发布模式下初始化错误
- Visual Studio 2010 SP1 中的 64 位整数初始化错误
- C++libPNG-简单初始化错误
- 结构数组-初始化错误
- 初始化错误
- 我不断收到函数初始化错误.(运行时检查失败 #3)