计算1-n的和(不用for, while, goto, if, else, switch, case和三目运算符, 也不用乘除法)---利用多态性

来源:互联网 发布:图文编辑器软件 编辑:程序博客网 时间:2024/05/16 08:38

     之前, 我们利用间接递归来实现了1-n的求和, 我们自己动态地选择了调用哪个函数。 仔细想一下, C++中的多态不就是专门干这个事情的么? 试一下:

#include <iostream>using namespace std;class A{public:virtual int getResult(int n){return 0;}};A *p[2] = {NULL, NULL};class B : public A{public:int getResult(int n){return p[!!n]->getResult(n - 1) + n;}};int main(){A a;B b;p[0] = &a;p[1] = &b;cout << p[1]->getResult(100) << endl;  // 5050return 0;}
      多态强大啊。

0 0