虚函数
这里主要是基类的指针问题,基类指针调用继承类中的对象,指向了继承类的函数。这里的(dream *dp=&p;);dp->f1();指的是继承类的f1()。
例子1#include <iostream>
using namespace std;
class dream
{
public:
virtual void f1()
{
cout<<"dream one car"<<endl;
}
virtual void f2()
{
cout<<"dream two house"<<endl;
}
void f3()
{
cout<<"childhold"<<endl;
}
};
class people:public dream
{
public:
void f1()
{
cout<<"car:benz"<<endl;
}
void f2()
{
cout<<"house:huge"<<endl;
}
void ff()
{
cout<<"it is my life"<<endl;
}
};
void main()
{
people p;
p.f1();
p.f2();
p.ff();//可以调用ff
cout<<endl;
dream d;
d.f1();
d.f2();
d.f3();
cout<<endl;
dream *dp=&p;
dp->f1();//可以调用带虚函数的函数
dp->f2();
//这样调用ff是错误的 dp->ff();
cout<<endl;}
例子2
#include<iostream>
using namespace std;
class A
{
public:
void f(){cout<<"a"<<endl;};
};
class B:virtual public A
{};
class C:virtual public A
{};
class D:public B,public C
{};
void main()
{
D d;
d.f();
d.B::f();//当不用虚函数是必须指定f()的来源否则报错
}
纯虚函数
基类中不能给虚函数有意义的现实,而把它声明为纯虚函数,实现留给了派生类去完成。看到上面的虚函数里面还是有函数体的,但是在纯虚函数中就没有函数体。
格式 virtual f()=0
纯虚函数让类先具有一个操作名称,没有操作内容,具体实现在继承类里。
含有纯虚函数的类叫抽象类,这种类不能声明对象,只能被继承。
c++支持编译时的多态和运行时的多态,编译多态通过重载函数实现。(以后再说吧)
例子1:
#include<iostream>
using namespace std;
class A
{
public:
void f1()
{
cout<<"111"<<endl;
}
virtual void f2()//虚函数
{
cout<<"222"<<endl;
}
virtual void f3()=0;//纯虚函数
};
class B:public A
{
public:
void f2()
{
cout<<"333"<<endl;
}
void f3()
{
cout<<"444"<<endl;
}
};
void main()
{
B b;
b.f1();
b.f2();
b.f3();
cout<<endl;
// A a; a类不能声明对象,否则报错
// a.f1();
}
例子2
#include<iostream>
using namespace std;
class TODAYdyd
{
public:
virtual void f1()=0;
};
class TOMORROWdyd:public TODAYdyd//public 后面没有冒号
{
public:
void f1()
{
cout<<"defend"<<endl;
}
};
void main()
{
TOMORROWdyd dyd;
dyd.f1();
cout<<endl;
TODAYdyd *p=&dyd;//TODAYdyd 不能有自己的对象,但是可以有指针,用法和虚函的指针一样。
p->f1();//效果等于dyd.f1();
}
关于虚函数的构造函数调用顺序的说明,看主函数的对象,对象的类继承了哪些类就要调用那些类的构造函数。构造函数的顺序是,1、先调用虚基类,然后调用基类2、按照继承顺序调用基类的构造函数。
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"AAAAA"<<endl;
m=0;
n=0;
}
A(int n,int m)
{
this->m=m;
this->n=n;
}
void disp()
{
cout<<n<<";"<<m<<endl;
}
int n,m;
};
class B
{
public:
B()
{
cout<<"BBBBB"<<endl;
}
};
class C
{
public:
C() {
cout<<"CCCCC"<<endl;
}
};
class D:public B,virtual public C,virtual public A
{
public:
D(){
cout<<"DDDDD"<<endl;
}
};
void main()
{
D aaa;
}
例子的来源:徐彤教程325 326 328