C++中的继承和动态绑定小结—一个例子

2017-04-13  本文已影响0人  fwei

抽象、继承和动态绑定是面向对象编程的核心思想,这里通过一个代码做一个简答的总结,其中主要的一些知识点,都写在代码的注释中。
exampleOOP.h 文件(对用到的基类和派生类做了定义)

#ifndef EXAMPLEOOP_H
#define EXAMPLEOOP_H
#include <iostream>

class base {
public:
    base() = default; //******显式声明默认构造函数,无参数
    base(int i){      //******自己定义的默认构造函数
        std::cout << "the based "<< i << 
            " class has been created !" << std::endl; 
    }
    void base_fun1() { 
        std::cout << "This is the fun1 of base" << std::endl; 
    }
    virtual void virtual_final()  final { //****final参数,该函数不可以再在派生类中定义,虽然他是一个虚函数
        std::cout << "final function" << std::endl; 
    }
    virtual void virtua_fun2(){ 
        std::cout << "this is the virtual funciton,from base" << std::endl; 
    }
    virtual ~base() {  //析构函数,必须声明为虚函数
        std::cout << "delete base " << std::endl; 
    }
};

class child : public base {
public:
    child(int i,int j):base(j) { //派生类中初始化基类
        std::cout << "the child "<< i 
            <<"  class has been created !" << std::endl; 
    }
    child(int i) : base(i){}
    void virtua_fun2() override {  //override 显式声明重写了派生类中的虚函数
        std::cout << "this is the virtual funciton,from child class" 
            << std::endl; 
    }
    void child_fun() { 
        std::cout << "this is the child function,only child have" 
            << std::endl; 
    }
    void virtua_fun2(int x) { 
        std::cout << "the same name of base_fun2, but define in child2" << std::endl; 
    }
    ~child() { 
        std::cout << "delete child" << std::endl;
    }
};

#endif
#include "exampleOOP.h"

int main() {
    static int i = 0;
    static int j = 0;
    base base_example(1);
    child child_example(2,3);   //先构建基类,在构建派生类
    
    // 关于派生类和基类的对象的一些规则的例子
    child_example.base_fun1();  //派生类访问基类的非虚函数函数
    child_example.virtua_fun2();    //派生类对象调用派生类的同名函数
    child_example.virtual_final(); //派生类可以使用基类的final函数,但不可以重新定义
    base_example.virtua_fun2();   //基类对象调用基类的函数
    //base_example.virtua_fun2()

    base * base_point = new child(1); //简单理解,可以认为base_point是一个“阉割版”的派生类指针,即这个指针对象只可以使用派生类继承的函数成员,而不能使用派生类自己特有的函数成员,在本例中,base_point不能调用virtua_fun2(int x)。
    base_point->base_fun1();//指向派生类类型的基类指针可以使用派生类中,继承的基类的函数
    base_point->virtua_fun2();//调用虚函数的时候,调用的是派生类的中定义的虚函数
    //base_point->virtua_fun2(1); 不能通过,因为这个函数虽然和虚函数有着同样的名字,但是参数不同,因此相当于是派生类中特有的函数,而派生类中特有的函数,只有通过派生类的对象、指针或引用来使用。
    delete base_point; //用完要删除,new完记得delete
    
    child child_example2(1);
    base &t = child_example2;
    t.virtua_fun2();//可以简单的记为,基类的引用对象,如果引用的是派生类,那么这个对象就可以看做是派生类对象
    t.base_fun1();// 可以使用基类的所有函数

    child *child_point = &child_example;
    child_point->virtua_fun2(2);//可以使用virtua_fun(int x)函数,相当于重载
    //delete child_point; 此处不能delete,因为child是指向了一个已经存在的对象,如果不再使用这个指针,可以使这个指针指向NULL 
    child_point = NULL;
    
    return 0;
}
*/

程序执行结果如下:

基类和派生类
上一篇 下一篇

猜你喜欢

热点阅读