// Vitual_Base.cpp : Defines the entry point for the console application. //抽象基类与纯虚函数 #include "stdafx.h" #include<stdlib.h> #include<iostream> using namespace std; class Point { private: double x, y; public: Point(double i, double j) :x(i), y(j)//使用参数列表 { } void print()const //防止在函数体内修改变量的值 { cout << "( " << x << ", " <<y<<")"<< endl; } }; //声明一个图形类,作为其他类的基类 class Figure//组合类 { private: Point center; public: Figure(double i = 0, double j = 0) :center(i, j)//注意复合类初始化与继承类初始化的异同 { } Point & location()//为了避免拷贝,不产生临时变量使用引用 { return center; } void move(Point p) { center = p;//改变图形的中心点 draw();//调用draw()函数对图形重新绘制 } //纯虚函数:虚函数只有声明,没有实现,函数体=0 virtual void draw() = 0;//绘制图形,但不知道是什么图形,因此并不知道他的具体实现 virtual void rotate(double) = 0;//旋转函数,也没有实现 }; //声明一个类。继承于图形类 class Circle :public Figure//派生类 { private: double radius; public: Circle(double i = 0, double j = 0, double r = 0) :Figure(i, j),radius(r) { } void draw()//对父类Figure中的纯虚函数进行实现 { cout << "A circle with center "; location().print();//打印圆的中心 cout << " and radius " << radius << endl; } void rotate(double a)//旋转一个圆,虽然没有任何效果,但必须rotate()函数必须实现 { cout << " no effect.\n"; } }; //声明一个正方形类,继承于图形类,与圆的实现基本类似 class Square :public Figure { private: double side;//边长 double angle;//与x轴的夹角 public: Square(double i = 0, double j = 0, double d = 0, double a = 0) :Figure(i, j) { side = d; angle = a; } void draw() { cout << "A square with center "; location().print(); cout << " side length " << side << ".\n" << " The angle between one side and the X-axis is " << angle << endl; } void rotate(double a) { angle += a; cout << "The angle between one side and the X-axis is " << angle << endl; } //顶点数 void vertices() { cout << "The Vertices of the square are: 3\n"; } }; int main() { Circle c(1, 2, 3); Square s(4, 5, 6); Figure *f = &c;//父类指针指向子类对象 Figure &g = s; Figure aFigure(10,10);//error不能构造抽象类的对象 f->draw(); f->move(Point(2, 2)); g.draw();//使用父类引用调用虚函数 g.rotate(1); g.move(Point(1, 1)); s.vertices(); system("pause"); return 0; } /*那么子类是不是必须实现基类中所有的纯虚函数? 是:因为子类不实现所有的纯虚函数子类依然是一个抽象类 不是:因为子类拥有了基类的函数,但是纯虚函数没有实现,因此子类必须实现才行 因此: (1) 纯虚函数:虚函数只有声明,函数体=0,就是一个纯虚函数,纯虚函数没有函数体 ,不需要实现,在子类里实现纯虚函数的具体功能 (2)抽象基类:拥有纯虚函数的类叫抽象基类,抽象类只能作为基类,不能构建对象,因 为抽象类中的纯虚函数没有函数体,即没有实现部分 (3)抽象类提供了不同子类对象的一个通用接口 (4)纯虚函数被定义在派生类中,如果派生类不重写基类的纯虚函数,则派生类也是一个 抽象类 */
C++之抽象基类与纯虚函数
最新推荐文章于 2023-02-24 00:37:34 发布