虚函数
加上一个virtual就行了。
#include <iostream>
using namespace std;
class A {
public:
A(int x):a(x) {}
virtual void display() {
cout << a << endl;
}
protected:
int a;
};
class B:public A {
public:
B(int x1,int x2):A(x1),str(x2){}
void display() {
cout<<a<<endl;
cout << str << endl;
}
private:
int str;
};
int main()
{
B b(1,2);
A *a=&b;
a->display();
return 0;
}
纯虚函数
virtual 函数类型 函数名 (参数列表)=0;
这样声明,然后再派生类中重新定义就行了,派生类中的重名函数不需要写virtual,如果需要再次派生,也可以加上。
#include <iostream>
#define Pi 3.14
using namespace std;
class Shape {
public:
Shape(double a=0):area(a){}
virtual double Area()=0;
virtual void Show() {
cout<<area<<endl;
}
protected:
double area;
};
class Circle:public Shape {
public:
Circle(double xx,double yy,double rr):Shape(),x(xx),y(yy),r(rr) {}
double Area() {
area=Pi*r*r;
return area;
}
virtual void Show() {
cout<<area<<endl
<<r<<endl
<<'('<<x<<','<<y<<')'<<endl;
}
friend ostream& operator <<(ostream &output,Circle &c);
private:
double x,y,r;
};
ostream& operator <<(ostream &output,Circle &c) {
output<<c.area<<endl
<<c.r<<endl
<<'('<<c.x<<','<<c.y<<')'<<endl;
return output;
}
int main()
{
Circle c(1,1,1);
c.Area();
Shape *s=&c;
s->Show();
cout<<c;
return 0;
}