企业网站如何建设报告,营销型网站开发公司,九寨沟城乡建设官方网站,网站源码怎么绑定域名在C中#xff0c;可以将虚函数声明为纯虚函数#xff0c;语法格式为#xff1a;
virtual 返回值类型 函数名 (函数参数) 0;
纯虚函数没有函数体#xff0c;只有函数声明#xff0c;在虚函数声明的结尾加上0#xff0c;表明此函数为纯虚函数。 最后的0并不表示函数返回…在C中可以将虚函数声明为纯虚函数语法格式为
virtual 返回值类型 函数名 (函数参数) 0;
纯虚函数没有函数体只有函数声明在虚函数声明的结尾加上0表明此函数为纯虚函数。 最后的0并不表示函数返回值为0它只起形式上的作用告诉编译系统“这是纯虚函数”。 包含纯虚函数的类称为抽象类Abstract Class。之所以说它抽象是因为它无法实例化也就是无法创建对象。原因很明显纯虚函数没有函数体不是完整的函数无法调用也无法为其分配内存空间。
抽象类通常是作为基类让派生类去实现纯虚函数。派生类必须实现纯虚函数才能被实例化。
纯虚函数使用举例
#include iostreamusing namespace std;//线class Line{public:Line(float len);virtual float area() 0;virtual float volume() 0;protected:float m_len;};Line::Line(float len): m_len(len){ }//矩形class Rec: public Line{public:Rec(float len, float width);float area();protected:float m_width;};Rec::Rec(float len, float width): Line(len), m_width(width){ }float Rec::area(){ return m_len * m_width; }//长方体class Cuboid: public Rec{public:Cuboid(float len, float width, float height);float area();float volume();protected:float m_height;};Cuboid::Cuboid(float len, float width, float height): Rec(len, width), m_height(height){ }float Cuboid::area(){ return 2 * ( m_len*m_width m_len*m_height m_width*m_height); }float Cuboid::volume(){ return m_len * m_width * m_height; }//正方体class Cube: public Cuboid{public:Cube(float len);float area();float volume();};Cube::Cube(float len): Cuboid(len, len, len){ }float Cube::area(){ return 6 * m_len * m_len; }float Cube::volume(){ return m_len * m_len * m_len; }int main(){Line *p new Cuboid(10, 20, 30);coutThe area of Cuboid is p-area()endl;coutThe volume of Cuboid is p-volume()endl;p new Cube(15);coutThe area of Cube is p-area()endl;coutThe volume of Cube is p-volume()endl;return 0;}
运行结果 The area of Cuboid is 2200 The volume of Cuboid is 6000 The area of Cube is 1350 The volume of Cube is 3375
本例中定义了四个类它们的继承关系为Line -- Rec -- Cuboid -- Cube。
Line 是一个抽象类也是最顶层的基类在 Line 类中定义了两个纯虚函数 area() 和 volume()。
在 Rec 类中实现了 area() 函数所谓实现就是定义了纯虚函数的函数体。但这时 Rec 仍不能被实例化因为它没有实现继承来的 volume() 函数volume() 仍然是纯虚函数所以 Rec 也仍然是抽象类。
直到 Cuboid 类才实现了 volume() 函数才是一个完整的类才可以被实例化。
可以发现Line 类表示“线”没有面积和体积但它仍然定义了 area() 和 volume() 两个纯虚函数。这样的用意很明显Line 类不需要被实例化但是它为派生类提供了“约束条件”派生类必须要实现这两个函数完成计算面积和体积的功能否则就不能实例化。
在实际开发中你可以定义一个抽象基类只完成部分功能未完成的功能交给派生类去实现谁派生谁实现。这部分未完成的功能往往是基类不需要的或者在基类中无法实现的。虽然抽象基类没有完成但是却强制要求派生类完成这就是抽象基类的“霸王条款”。
抽象基类除了约束派生类的功能还可以实现多态。请注意第 51 行代码指针p 的类型是 Line但是它却可以访问派生类中的 area() 和 volume() 函数正是由于在 Line 类中将这两个函数定义为纯虚函数如果不这样做51 行后面的代码都是错误的。我想这或许才是C提供纯虚函数的主要目的。 关于纯虚函数的几点说明
1) 一个纯虚函数就可以使类成为抽象基类但是抽象基类中除了包含纯虚函数外还可以包含其它的成员函数虚函数或普通函数和成员变量。
2) 只有类中的虚函数才能被声明为纯虚函数普通成员函数和顶层函数均不能声明为纯虚函数。如下例所示 //顶层函数不能被声明为纯虚函数void fun() 0; //compile errorclass base{public ://普通成员函数不能被声明为纯虚函数void display() 0; //compile error};