C++ 抽象类与接口
2016-10-11 22:37
204 查看
C++中抽象类是指至少包含一个纯虚函数的类,一般格式如下:
class <类名>
{
public:
virtual <类名> <函数名>(参数列表) = 0;
}
接口的实现是通过定义子类来继承父类(抽象类),在子类中对父类中的纯虚函数进行定义,举一个简单的实例,如下:
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; }
相关文章推荐
- C++中的抽象类以及接口的区别联系
- C++中抽象类和接口类的区别
- C++接口和抽象类
- C++中的抽象类以及接口的区别联系
- C++中的抽象类以及接口的区别联系
- C++中抽象类和接口类的区别(转)
- C++中的抽象类以及接口的区别联系
- C++中的抽象类以及接口的区别联系
- C++中的抽象类以及接口的区别联系
- c++标准的 接口和抽象类
- [收集]c++抽象类、纯虚函数以及巧用纯虚析构函数实现接口类
- C++中的抽象类以及接口的区别联系
- C\C++ 程序员从零开始学习Android - 个人学习笔记(八) - java基础 - 继承、抽象类、接口、内部类(待续)
- [收集]c++抽象类、纯虚函数以及巧用纯虚析构函数实现接口类
- C++中抽象类和接口类的区别
- C++中抽象类和接口类的区别(转载)
- C++ 中的 抽象类 和 接口
- C++中抽象类和接口的区别
- c++中抽象类与接口的区别
- c++虚类相当与java里面的抽象类,与接口的不同之处