执行 c++ 代码时出错
Error while executing the c++ code
class Fruit{
};
class Banana: public Fruit
{
public:
bool isRipe(){
if (mColor == ‘y’){
return true;
}
else{
return false;
}
}
};
main(){
Banana banana;
banana.setColor(‘y’);
if(banana.isRipe()){
cout << “banana is ready to eat” << endl;
}
else{
cout << “banana is not ready to eat” << endl;
}
}
这是需要编译的代码,但抛出以下错误:-
$fruit.cpp||In member function 'bool Banana::isRipe()':|
$fruit.cpp|17|error: 'y' was not declared in this scope|
$fruit.cpp||In function 'int main()':|
$fruit.cpp|28|error: 'class Banana' has no member named 'setColor'|
$fruit.cpp|28|error: 'y' was not declared in this scope|
$fruit.cpp|30|error: 'cout' was not declared in this scope|
$fruit.cpp|30|error: expected ';' before 'is'|
$fruit.cpp|33|error: 'cout' was not declared in this scope|
$\fruit.cpp|33|错误:在"is"之前应为";"|||=== 生成失败:32 个错误、0 个警告(0 分钟、0 秒(===|
我正在尝试将基类用于给定的 Fruit 派生类,但没有正确处理。任何帮助,不胜感激。
这个‘y’
和这个“banana is ready to eat”
似乎很可疑:引号错误
它们应该是'y'
和"banana is ready to eat"
编译器希望"普通"""
引号来标识单个字符的字符串和''
我完全同意fuzzything44和Gian Paolo的评论。顺便说一下,应该指出的是,当前的 ISO C++ 标准要求 main
函数的声明具有类型(例如int main ()
(。
你的代码有很多错误,我怀疑你根本没有考虑过。
$\水果.cpp||在成员函数 'bool Banana::isRipe((':|
$\fruit.cpp|17|错误:未在此范围内声明"y"|
@Gian Paolo 一针见血地回答了不正确的引号:
编译器希望"普通"
""
引号来标识单个字符的字符串和''
。
$\水果.cpp||在函数 'int main((' 中:|
$\fruit.cpp|28|错误:"类香蕉"没有名为"setColor"的成员|
您实际上没有声明一个名为 setColor
的函数。也许你的Fruit
类是为了声明它(因为所有的水果大概都有颜色(,或者你的Banana
类是为了声明它,无论哪种方式,你都需要在使用它之前声明这个函数。同样,您也未能声明mColor
:
class Fruit
{
public:
void setColor(char col) { mColor = col };
protected:
char mColor;
};
在这一点上,您可能希望为此使用enum
,因为它比char
更有意义。g
代表什么颜色,或者b
什么颜色?
class Fruit
{
public:
enum class Color { Yellow, Red, Blue, Green };
void setColor(Color c) { mColor = c; }
protected:
Color mColor;
};
$\fruit.cpp|28|错误:未在此范围内声明"y"|
$\fruit.cpp|30|错误:在"is"之前应为";"|
由于未能在字符周围使用正确的引号,因此编译器假定它是一个变量。您需要使用单引号:
if (mColor == 'y')
但是,如果您使用上面指定的enum
,它将在逻辑上更流畅地流入:
if (mColor == Color::Yellow)
$\fruit.cpp|30|错误:未在此范围内声明"cout"|
$\fruit.cpp|33|错误:在此范围内未声明"cout"|
你要么不using namespace std
,要么不包括iostream.h
,但我打赌猜测并说两者。您需要包含声明std::cout
和std::endl
的文件,并指定它们来自的命名空间:
#include <iostream> // cout, endl
...
std::cout << "banana is ready to eat" << std::endl;
另请注意,我已将字符串文字的引号更改为双引号。
值得一提的是两件事:
1.继承一个空类是没有意义的,就像你和Fruit
一样.
2. 正如@EuGENE在他们的答案中指出的那样,您需要为所有函数指定返回类型,main()
包含!与 C 不同,C++不会假设您默认返回int
:
int main()
我的建议是将来要多加小心:放慢速度,更频繁地编译,并阅读编译器告诉您的错误。
- 在Linux for Windows上编译C++代码时出错
- 尝试将另一个子句添加到代码中时出错
- 将代码从 Python 转换为 C++ 时出错
- <limits> 使用 VSC2019 编译旧代码时出错
- 使用 Visual Studio 代码读取 C++ 中的输入流时出错
- 在OpenGL中使用程序集代码渲染视频时出错
- 编译以下代码时出错
- Boost FFT示例-编译时出错,这段代码在做什么
- 编译在 Python 代码内部调用的 C++ 代码时出错,使用 Boost Python
- C++:为什么这段代码会出错?多元线性回归
- 混合开放MP/MPI代码中的多线程发送/接收时出错
- 将节点 js 代码集成到 cpp 库时出错
- 构建代码时出错
- 在字符串流中使用来自 github 的代码时出错
- 在主代码中调用 .hpp 函数时出错
- 将 find_if() 与数组一起使用的代码段中出错
- 我在字数C++的代码中哪里出错了
- 尝试从 Github 编译 OpenCV QT 代码时出错
- 编译创建 Eigen::ThreadPoolDevice 对象的代码时出错
- 编译 .cu 与 .cpp:即使没有任何 CUDA 代码,编译器也会出错