虚函数和纯虚函数

虚函数
加上一个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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值