C++多态


C++多态

#include <iostream>
using namespace std;
class Wood{
protected:
    int height;
    int cost;
public:
    Wood(int height,int cost)
    {
        this->height=height;
        this->cost=cost;
    }
    virtual void show()
    {
        cout<<height<<endl;
    }
};
class Table:public Wood{
public:
    Table(int height,int cost): Wood(height,cost){}
    void show()
    {
        cout<<"Table:"<<height<<endl;
    }
};
int main()
{
    Table t1(55,61);
	Wood *ptr=&t1;
    ptr->show(); // Table:55
    return 0;
}

2021-5-22-15-53

  • 当类中出现了虚函数,该类中就会生成一个虚函数指针,该虚函数指针指向虚函数表,虚函数表实质上来说是一个数组
  • 当基类中有虚函数时,派生类中也会生成一个虚函数指针,指向虚函数表,这个表继承了基类虚函数表的元素
  • 如果重写虚函数就会修改虚函数表的内容,让其指向自己的函数
#include <iostream>
using namespace std;
class Wood{
public:
    Wood(int height,int cost)
    {
        this->height=height;
        this->cost=cost;
    }
    virtual void show()
    {
//        cout<<height<<endl;
        cout<<"hell"<<endl;

    }
protected:
    int height;
    int cost;
};
class Table:public Wood{
public:
    Table(int height,int cost): Wood(height,cost){}
    void show()
    {
        cout<<"Table:"<<height<<endl;
    }
};
typedef void (*Myfunc)();
int main()
{
    Wood w1(12,36);
    Table t1(55,61);
    long long *wptr=(long long *)(((long long *)(*((long long *)&w1)))[0]);
    long long *tptr=(long long *)(((long long *)(*((long long *)&t1)))[0]);
    Myfunc ptr=(Myfunc)wptr;
    ptr(); // hell
    cout<<wptr<<endl; //0x402d80
    cout<<tptr<<endl; //0x402e40
    return 0;
}

文章作者: dyl
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 dyl !
 上一篇
C++流 C++流
C++输入输出基本概述以及方法调用,流向内存的数据称为输入流,流出内存的数据称为输出流,该视频来自博主b站总结
2023-12-10 dyl
下一篇 
C++ lamdba表达式 C++ lamdba表达式
本文讲解lamdba表达式基本语法,本文对于初学C++萌新而言十分友好,lamdba表达式在C++使用广泛,掌握lambda表达式对于灵活使用C++非常重要
2023-12-10 dyl
  目录