c++虚函数:
1.纯虚函数:
<pre name="code" class="cpp"><span style="font-size:18px;">#include <iostream>
class A{
private:
int a;
public:
virtual void f()=0;
};
class B:public A{
private:
int a;
public:
B(int i):a(i) {};
virtual void f(){ std::cout<<"classB:"<<a<<std::endl;}
};
int main()
{
B b(10);
A *a= &b;
a->f();
return 0;
}</span>
输出结果是: classB
注意:
1:在基类中,函数不给出定义,在末尾写 “=0”,否则会报错。
2:在类B中,关键virtual 可有可无,在B中一定得给出函数f的定义。
3:基类不能被实例化(含有纯虚函数的基类是抽象类,不能实例化),只能用指针调用其他类的成员函数。
非纯虚函数:
#include<iostream>
class A{
private:
int a;
public:
A(int i): a(i) {} ;
virtual void f()
{
std::cout<<"classA"<<a<<std::endl;
}
};
class B:public A{
private:
int a;
public :
B(int i):A(i) {
a= i;
};
void f()
{
std::cout<<"classB"<<a<<std::endl;
}
};
int main(){
A a(10);
B b(20);
A *pa;
B *pb;
pa= &a;
pa->f();
pa= &b;
pa->f();
pb= &b;
pb->f();
return 0;
}
输出结果:
classA10
classB10
classB10
注意:1:不能pb = &a;
2: 实现是通过隐藏基类的方法。
在继承过程中,如果子类有动态内存分配如new非配内存空间的情况,需要将基类的析构函数写成虚函数,不然将会导致内存泄露。