01虚函数与抽象类

联编

#include<iostream>
using namespace std;


const double PI = 3.1415926;

class cpoint
{
public:
	cpoint(double a, double b)
	{
		x = a;
		y = b;
	}
	double area()
	{
		return 0;
	}
private:
	double x, y;
};

class ccircle :public cpoint
{
public:
	ccircle(double a, double b, double c) :cpoint(a, b)
	{
		r = c;
	}
	double area()
	{
		return PI * r * r;
	}
private:
	double r;
};


class cractangle :public cpoint
{
public:
	cractangle(double a, double b, double c, double d) :cpoint(a, b)
	{
		w = c;
		h = d;
	}
private:
	double w, h;
};

void funcarea(cpoint& p)
{
	cout << "area = " << p.area() << endl;
}
int main()
{
	ccircle cobj(5.5, 6.6, 10);
	funcarea(cobj);

	cractangle cobjs(3, 4, 5, 6);
	funcarea(cobjs);
	return 0;
}

输出结果均为0.
在这里插入图片描述
基类cpoint加上virtual
在这里插入图片描述
自定义写一个:

class Animal
{
public:
	virtual void callfunc();//虚函数
private:
	string name;
};

void Animal::callfunc()
{
	cout << "我不会叫" << endl;
}
class cat :public Animal
{
public:
	cat(int _age, string _name)
	{
		age = _age;
		name = _name;
	}
	void callfunc()
	{
		cout << name << "猫叫" << endl;
	}
private:
	string name;
	int age;
};


class dog :public Animal
{
public:
	dog(int _age, string _name)
	{
		name = _name;
		age = _age;
	}
	void callfunc()
	{
		cout << name << "狗叫" << endl;
	}
private:
	string name;
	int age;
};

void callfunc(Animal* p)//传递不同的对象实参,可以调用对应的成员函数,实现多态功能
{
	p->callfunc();
}

int main()
{
	cat a(18, "大猫");
	cat a1(1, "小猫");
	dog b(18, "傻狗");
	callfunc(&a);
	callfunc(&b);
	return 0;
}

抽象类

抽象类
**纯虚函数:**不能初始化定义。
virtual void callfunc() = 0;

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值