6-1 多态性与虚函数

6-1 多态性与虚函数
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description
通过本题目的练习可以掌握多态性的概念和虚函数的定义和使用方法

要求定义一个基类Pet,它有一个成员函数Speak()用于输出pet的叫声。;派生类Dog和Cat从基类Pet派生而来。他们从基类继承并重新改写了speak()函数,分别用于输出Dog类和Cat类的叫声。要求利用虚函数编写代码,使得程序能够输出下面的内容。

Input

Output

输出数据共有3行,本题目要求输出内容必须与示例中的相同。

Example Input
Example Output
How does a pet speak ?
miao!miao!
wang!wang!
Hint

Author
黄晶晶

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;

class pet
{
public:
    virtual void speak() const
    {
        cout << "How does a pet speak ?" << endl;
    }

};
class cat :public pet
{
public:
    void speak()const
    {
        cout << "miao!miao!" << endl;
    }
};
class dog :public pet
{
public:
    void speak()const
    {
        cout << "wang!wang!" << endl;
    }
};

void fun(pet * ptr)
{
    ptr->speak();
}
int main()
{
    pet perp;
    cat perc;
    dog perd;
    fun(&perp);
    fun(&perc);
    fun(&perd);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值