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 |错误:预期';'之前'是'| || ===构建失败:32个错误,0个警告(0分钟,0秒(秒))=== |
我正在尝试使用基类来获取Fruit的给定派生类但不能正确使用它。任何帮助表示赞赏。
答案 0 :(得分:2)
此‘y’
和此“banana is ready to eat”
似乎有疑问:错误的引号
他们应该是'y'
和"banana is ready to eat"
编译器需要“普通”""
引号来标识字符串,''
表示单个字符
答案 1 :(得分:1)
我完全赞同 fuzzything44 和 Gian Paolo 评论。顺便说一句,应该指出当前的ISO C ++标准需要main
函数的声明具有类型(例如int main ()
)。
答案 2 :(得分:0)
你的代码有很多错误,我怀疑你是否已经考虑过它。
$ \ fruit.cpp ||在成员函数'bool Banana :: isRipe()'中:|
中声明
$ \ fruit.cpp | 17 |错误:'y'未在此范围|
@Gian Paolo用their answer标注了不正确的引号:
编译器需要“普通”
""
引号来标识字符串,并为单个字符标识''
。
$ \ fruit.cpp ||在函数'int main()'中:|
的成员
$ \ fruit.cpp | 28 |错误:'class Banana'没有名为'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 |错误:预期';'在'是'|
之前
由于您未能在字符周围使用正确的引号,因此编译器假定它是变量。您需要使用单引号:
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;
另请注意,我已将引号更改为字符串文字的双引号。
值得一提的是两件事:
继承一个空课是没有意义的,就像你和Fruit
一样
2.作为@EuGENE points out in their answer,您需要为所有函数指定返回类型,main()
包含!与C不同,C ++不会假设您的意思是默认返回int
:
int main()
我的建议是在将来要更加小心:慢点,更频繁地编译,并阅读编译器告诉你的错误。