执行 c++ 代码时出错

Error while executing the c++ code

本文关键字:出错 代码 c++ 执行      更新时间:2023-10-16
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"

编译器希望"普通"""引号来标识单个字符的字符串和''

我完全同意fuzzything44Gian 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::coutstd::endl的文件,并指定它们来自的命名空间:

#include <iostream> // cout, endl
...
std::cout << "banana is ready to eat" << std::endl;

另请注意,我已将字符串文字的引号更改为双引号。

值得一提的是两件事:
1.继承一个空类是没有意义的,就像你和Fruit一样.
2. 正如@EuGENE在他们的答案中指出的那样,您需要为所有函数指定返回类型,main()包含!与 C 不同,C++不会假设您默认返回int

int main()

我的建议是将来要多加小心:放慢速度,更频繁地编译,并阅读编译器告诉您的错误。