首页 > 代码库 > C++ 虚函数,纯虚函数的一些问题

C++ 虚函数,纯虚函数的一些问题

#include <iostream>using namespace std;#define cendl cout << endl;class AA{//这是一个纯虚函数public :    virtual void fun() = 0;};class A{    int data_a;public:    A(){        data_a = 1;        cout << "A " ;    }    A(int a){        data_a = a;        cout << "A(a) " ;    }    void show(){        cout << data_a<<  ;    }    virtual void fun(){        cout << "this is A ";    }    ~A(){        cout << "~A " ;    }};class B : public A{    int data_b;public:    B(){        data_b = 2;        cout << "B " ;    }    B(int a, int b) :A(a){        data_b = b;        cout << "B(a) " ;    }    void show(){        A::show();        cout << data_b <<  ;    }    virtual void fun(){        cout << "this is B ";    }    ~B(){        cout << "~B " ;    }};

class C :public A{
int data_c;
public:
C(){ data_c = 3; cout << "C " ; }
C(int a, int b) :A(a){
data_c = b;
cout << "C(a) " ;
}
void show(){
A::show();
cout << data_c << ‘ ‘;
}
virtual void fun(){
cout << "this is C ";
}
~C(){
cout << "~C " ;
}
};

int main()

{

A *a1 = new A(2);
cendl;
A *a2 = new B(2,3);
cendl;
A *a3 = new C(2, 3);
cendl;
a1->fun();
cendl;
a2->fun();
cendl;
a3->fun();
cendl;
delete a1;
cendl;
delete a2;
cendl;
delete a3;
system("pause");
return 0;

}

虚函数的作用主要是用作多态,定义一个基类的指针指向子类,可以产生不同的调用效果。如上面的程序输出如下:

技术分享

可以看出同样是基类的指针但是指向不用的子类是调用的是各个子类的fun函数。同时在delete的时候都是调用A的析构函数,没有调用子类的构造函数,不知道这是为啥

 

C++ 虚函数,纯虚函数的一些问题