基类重载的函数继承下来为什么不能调用,求各位大佬指点一二,在这里小白先谢过大家!
#include <iostream>#include <string>
using namespace std;
class Animal
{
public:
string mouth;
Animal(string name);
void Eat(); //吃
void Eat(int eatCount);
void Sleep(); //睡觉
void Drool(); //流口水
protected:
string name;
};
Animal::Animal(string name)
{
this->name = name;
cout << name << endl;
}
void Animal::Eat(int eatCount)
{
cout<<"我吃了"<<eatCount<<"碗馄饨"<<endl;
}
class Pig : public Animal
{
public:
void climb();
void Eat();
Pig(string name);
};
Pig::Pig(string name) : Animal(name)
{
;
}
class Turtle : public Animal
{
public:
Turtle(string name);
void Swim();
void Eat();
};
Turtle::Turtle(string name) : Animal(name)
{
;
}
void Animal::Eat()
{
cout << "I'm eatting!And the lunch is very delicous!^_^" << endl;
}
void Animal::Sleep()
{
cout << "I'm sleeping!Don't disturb me!Else I'll fight with you!!!T_T" << endl;
}
void Animal::Drool()
{
cout << "我是公的,看见美女我就流口水!我正在留口水!^_^" << endl;
}
void Pig::Eat()
{
Animal::Eat();
cout << name << "正在吃鱼。。。。。。^_^" << endl;//覆盖基类eat()
}
void Pig::climb()
{
cout << name << ":我是一只漂亮的小母猪,我会上树!我正在爬树。。。" << endl;
}
void Turtle::Eat()
{
Animal::Eat();
cout << name << "正在吃东坡肉。。。。。。^_^" << endl;//覆盖基类eat()
}
void Turtle::Swim()
{
cout << name << ":我是一只小甲鱼,当母猪想抓我的时候,我就游到海里。。哈哈。。" << endl;
}
int main()
{
int eatCount=15;
cout << "这只猪的名字叫作:";
Pig pig("小猪猪");
pig.climb();
pig.Eat();
pig.Eat(eatCount); //这里会报调用的参数过多,为什么?????????????????????????????
cout << "这只乌龟的名字叫作:";
Turtle turtle("小甲鱼");
turtle.Eat();
turtle.Swim();
return 0;
} 本帖最后由 superbe 于 2019-9-29 01:22 编辑
子类重写(override)基类成员函数时,会隐藏基类中同名函数,基类中重载的同名成员函数也被隐藏。
解决方法1:
class Pig : public Animal
{
public:
using Animal::Eat; //增加这行
void climb();
void Eat();
Pig(string name);
};
解决方法2:
原来pig.Eat(eatCount);这行修改成这样: pig.Animal.Eat(eatCount);
页:
[1]