#include <iostream> using namespace std; class Fract{ int n; int d; public: Fract():n(0),d(1) { } Fract(int an, int ad):n(an),d(ad) { reduce(); } void reduce() { if (d<0) { d = -d; n = -n; } if (n==0) { cout << "d==0 !!" << endl; } for (int i=d; i>1; i--) { if (n%i==0 && d%i==0) { n/=i, d/=i; break; } } } virtual void show() { cout << n << '/' << d << endl; } virtual double value() { return (double)n/d; } }; class Dai : public Fract{ int i; public: Dai():i(0) { } Dai(int ai , int an, int ad):i(ai), Fract(an, ad) { } void show() { cout << i << '(' ; Fract::show(); } double value() { return i+ Fract::value(); } }; int main() { Fract d1; Dai d2(2, 12, 16); Fract *p = NULL; p = &d1; p->show(); cout << "d1=" << p->value() << endl; p = &d2; //指针 实现 多态 p->show(); cout << "d2=" << p->value() << endl; Fract& d = d2; //引用 实现 多态 d2.show(); cout << "d2=" << d2.value() << endl; cout << "d3=" << d3.value() << endl; return 0; }
多态 virtual
最新推荐文章于 2023-09-05 21:16:36 发布