1 Star 0 Fork 1

llongger/Code_C++

forked from GodOuO/Code_C++ 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
38.polymorphic.cpp 1.07 KB
一键复制 编辑 原始数据 按行查看 历史
GodOuO 提交于 2023-03-15 04:07 . Train
#include<iostream>
#include<string>
using namespace std;
//多态
class Animal
{
private:
/* data */
public:
Animal(/* args */);
virtual void speak(){ //父类 函数进行虚函数
cout<<"Cat is Speaking!"<<endl;
}
};
Animal::Animal(/* args */)
{
}
class Cat:public Animal
{
private:
/* data */
public:
Cat(/* args */);
void speak(){
cout<<"Cat is Speaking!"<<endl;
}
};
Cat::Cat(/* args */)
{
}
class Dog:public Animal
{
private:
/* data */
public:
Dog(/* args */);
virtual void speak(){
cout<<"Dog is Speaking!"<<endl;
}
};
Dog::Dog(/* args */)
{
}
//地址早绑定,编译阶段「确定函数地址」
//virtual 父类函数 实现虚函数,支持地址晚绑定
void doSpeak(Animal &a){ //Animal & a = cat;
a.speak();
}
void test01(){
Cat cat;
doSpeak(cat); //允许父子之间的类型转换
Dog dog;
doSpeak(dog);
}
void test02(){
cout<<sizeof(Animal)<<endl; //指针8字节,Animal 类
}
int main(){
//test01();
test02();
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/llongger/codeCpp.git
git@gitee.com:llongger/codeCpp.git
llongger
codeCpp
Code_C++
master

搜索帮助

D67c1975 1850385 1daf7b77 1850385