C++继承

来源:互联网 发布:迈克尔芬利数据 编辑:程序博客网 时间:2024/06/05 20:12

在C++中的父子类的一些注意点:
1、子类和父类指针的包容性
2、子类覆盖父类的同名函数方法
3、父类的析构函数定义成虚函数,防止子类的析构函数不被调用
4、关于虚函数的注意点【在内存中占用四个字节的内存用于指向虚函数表】
5、

#include <iostream>#include <string>using namespace std;class Father{    public:        Father(int a = 0):a(a){cout << "父类构造函数" << endl;}        ~Father(){cout << "父类析构函数" << endl;}        //virtual ~Father(){cout << "父类 virtual 析构函数" << endl;}        void get()const {cout << "我是父亲" << endl;}    private:        int a;};class Child : public Father{    public:        Child(int a = 0):a(a){cout << "子类构造函数" << endl;}        ~Child(){cout << "子类析构函数" << endl;}        //virtual ~Child(){cout << "子类 virtual 析构函数" << endl;}        void get()const {cout << "我是儿子" << endl;}    private:        int a;};int main(void){    //Father *f = new Father;    Father *f = new Child;    //f->get();    delete f;    //Child c;    //c.Father::get();}
0 0
原创粉丝点击