您的位置:首页 > 编程语言 > C语言/C++

C++ 抽象类与接口

2016-10-11 22:37 204 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: