C++学习笔记 —— struct实现继承与const函数多态

参考文章
https://blog.csdn.net/IT_job/article/details/79183810
https://blog.csdn.net/puppet_master/article/details/48751575

Struct与class关键字的区别:

使用struct也可以实现继承多态,那我们还要class关键字又什么用呢
唯一区别就是:struct与class唯一不同的是struct默认的关键字是public, class默认的关键字是private。
使用class更好的进行权限访问控制,当然struct也可以设置关键字为private

const函数的多态问题

下面代码重写了三个函数:注意加const的常函数。
这里一个知识点,注意,当我们把父类函数设置为const,子类对应同名的非const函数不是继承来的,所以他没有重写该sleep函数,而是一个新的sleep,所以sleep没有实现多态。

#include <iostream>

using namespace std;

struct animal
{
    
    
public:
    animal() : age(1) {
    
    }       //构造函数
    ~animal() {
    
    }               //析构函数
    
    virtual int getAge() const //加const表示这个函数为常成员函数,常成员函数不能改变成员变量值
    {
    
    
        return age;
    }

    void setAge(int set_age) //可重新设置年龄
    {
    
    
        age = set_age;
    }

    virtual void speak() //说
    {
    
    
        cout << "animal speak!!!" << endl;
    }

    virtual void sleep() const //睡觉
    {
    
    
        cout << "animal sleep!!!" << endl;
    }

protected:
    int age = 8;
};

struct cat : public animal
{
    
    
public:

    virtual int getAge() const //加const表示这个函数为常成员函数,常成员函数不能改变成员变量值
    {
    
    
        cout << "cat age is " << age << endl;
        return age;
    }
    virtual void speak() //说
    {
    
    
        cout << "cat speak!!!" << endl;
    }
    virtual void sleep() //睡觉
    {
    
    
        cout << "cat sleep!!!" << endl;
    }


};

int main()
{
    
    
    animal *a = new cat; //多态
    a->speak();          //cat speak!!!
    a->sleep();          //animal sleep!!!  
    a->getAge();         //这里子类getage也是const所以这里实现了多态,因为他重写了该const函数
    return 0;
}

猜你喜欢

转载自blog.csdn.net/chongbin007/article/details/107146343