继承和多类的基础(C++)
代码一:
#include <iostream>
using namespace std;
class Fish
{
public:
bool isFreshWaterFish;
void Swim()
{
if (isFreshWaterFish)
cout << "Swims in lake" << endl;
else
cout << "Swims in sea" << endl;
}
};
class Tuna: public Fish
{
public:
Tuna()
{
isFreshWaterFish = false;
}
};
class Carp: public Fish
{
public:
Carp()
{
isFreshWaterFish = true;
}
};
int main()
{
Carp myLunch;
Tuna myDinner;
cout << "Getting my food to swim" << endl;
cout << "Lunch: ";
myLunch.Swim();
cout << "Dinner: ";
myDinner.Swim();
return 0;
}
通过公有继承,Tuna和Carp类将暴露基类共有方法swim
代码二:
#include <iostream>
using namespace std;
class Fish
{
public:
void Swim()
{
cout << "Fish swims!" << endl;
}
};
class Tuna:public Fish
{
public:
// override Fish::Swim
void Swim()
{
cout << "Tuna swims!" << endl;
}
};
void MakeFishSwim(Fish& InputFish)
{
// calling Fish::Swim
InputFish.Swim();
}
int main()
{
Tuna myDinner;
// calling Tuna::Swim
myDinner.Swim();
// sending Tuna as Fish
MakeFishSwim(myDinner);
return 0;
}
其中void MakeFishSwim(Fish& InputFish)将传入都看作Fish基类
代码三:
class Fish
{
public:
virtual void swim()
{
cout <<"Fish swim!!!"<<endl;
}
};
class Tuna :public Fish
{
public:
void swim()
{
cout << "Tuna swim in the sea" << endl;
}
};
class Carp :public Fish
{
public:
void swim()
{
cout << "Carp can swim in the lake" << endl;
}
};
void MakeFishSwim(Fish&inputFish)
{
//
inputFish.swim();
}
int main()
{
Carp myLunch;
Tuna myDinner;
MakeFishSwim(myDinner);
MakeFishSwim(myLunch);
system("pause");
return 0;
}
其中virtual 虚函数的优先级在派生类之后,这是典型的降级