实验五

1.(1)在多层继承中,派生类中出现与基类同名成员时,通过对象名.成员名的方式,访问的成员什么?

访问的是这个对象所在的成员,不是一定访问基类。

(2)通过基类指针访问派生类对象时,基类中成员函数有无关键字virtual,访问的成员分别是什么?

有关键字virtual时访问的是派生类的成员

无关键字virtual时访问的是基类的成员

3.设计并实现一个机器宠物类MachinePets。

#ifndef CATPETS_H
#define CATPETS_H
#include"machinepets.h"
#include<string>
#include<iostream>
using namespace std;
class PetCats :public MachinePets {
public:
    PetCats(const string s) :MachinePets(s) { 
    }
    string talk() {
        return (" says 喵~喵~喵");
    }
};
#endif
catpets.h
#ifndef DOGPETS_H
#define DOGPETS_H
#include<iostream>
#include<string>
#include"machinepets.h"
using namespace std;
class PetDogs :public MachinePets {
public:
    PetDogs(const string s) :MachinePets(s){ }
    string talk() {
        return (" says 汪~汪~汪");
    }

};
#endif
dogpets.h
#ifndef MACHINEPETS_H
#define MACHINEPETS_H
#include<string>
using namespace std;
class MachinePets {
public:
    MachinePets() {}
    MachinePets(const string s) :nickname(s) {}
    void getNickname(){cout<<nickname;}
    virtual string talk() = 0;
private:
    string nickname;
};
#endif
machinepets.h
#include <iostream>
#include<string>
#include"machinepets.h"
#include"catpets.h"
#include"dogpets.h"
using namespace std;
void play(MachinePets *ptr)
{
    ptr->getNickname();
    cout <<ptr->talk()<<endl;
}
int main()
{
    PetCats cat("miku");
    play(&cat);
    PetDogs dog("da huang");
    play(&dog);
    system("pause");
    return 0;
}
main.cpp

 

 

实验感想:

1.根据此次实验了解了纯虚函数和抽象类的定义,使用,以及判断。

2.加深了类的继承和派生的用法。

3.体会了基类指针可以指向派生类,基类是多态类型时,通过该指针调用基类的虚函数时,实际执行的是由派生类决定的。

 

posted on 2019-06-02 22:19  飞羽0-0  阅读(131)  评论(2)    收藏  举报