C++ 抽象类与接口

C++中抽象类是指至少包含一个纯虚函数的类,一般格式如下:

class <类名>

{

public:

virtual <类名> <函数名>(参数列表) = 0;

}

接口的实现是通过定义子类来继承父类(抽象类),在子类中对父类中的纯虚函数进行定义,举一个简单的实例,如下:

/**
C++ 接口是使用抽象类来实现的
如果类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类。纯虚函数是通过在声明中使用 "= 0" 来指定的
*/

#include 
   
   
    
    

using namespace std;

class Shape
{
public:
	virtual int getArea() = 0;

	void setWidth(int _width)
	{
		width = _width;
	}

	int getWidth()
	{
		return width;
	}

	void setHeight(int _height)
	{
		height = _height;
	}

	int getHeight()
	{
		return height;
	}

private:
	int width;
	int height;
/*
//用 protected 封装变量,在 public 中就不需要再定义函数(getWidth()、getHeight())来返回封装成私有变量的值 
protected:
	int width;
	int height;
*/
};

class Rect : public Shape
{
public:
	int getArea()
	{
		//return width * height;
		return getWidth() * getHeight();
	}
};

class Triangle : public Shape
{
public:
	int getArea()
	{
		//return (width * height)/2;
		return (getWidth() * getHeight())/2;
	}
};

int main()
{
	Rect r;
	Triangle t;

	r.setHeight(10);
	r.setWidth(20);
	cout << "rectArea: " << r.getArea() << endl;

	t.setHeight(10);
	t.setWidth(20);
	cout << "triangleArea: " << t.getArea() << endl;

	return 0;
}

   
   

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值