进阶之路

首页 新随笔 管理

46. 求 1+2+ … +n。

要求:不用乘除法、for、while、if、else、switch、case 以及条件判断语句(A?B:C)。

a. 利用构造函数求解

#include <iostream>
using namespace std;

class Sum{
public:
    Sum() {++n; sum += n;}
    static void reset() {sum = n = 0;}
    static int getSum(){ return sum;}
private:
    static int n;
    static int sum; 
};
int Sum::n = 0;
int Sum::sum = 0;

int solution(int n)
{
    Sum::reset();
    Sum *p = new Sum[n];
    delete[] p;
    return Sum::getSum();
}

int main()
{
    cout << solution(100) << endl;
    cout << solution(1000) << endl;
    cout << solution(100) << endl;
    return 0;
}
b. 利用虚函数函数指针求解
#include <iostream>
using namespace std;
class Base;
class Base* A[2];
class Base{
public:
    virtual int sum(int n) { return 0; }
};
class Dirived: public Base{
public:
    int sum(int n)
    {
        return A[!!n]->sum(n-1) + n;
    }
};
int main()
{
    A[0] = new Base;
    A[1] = new Dirived;

    cout << A[1]->sum(100) << endl;
    cout << A[1]->sum(1000) << endl;
    cout << A[1]->sum(100) << endl;
    return 0;
}

利用函数指针
#include <iostream>
using namespace std;

typedef int (*F)(int n);
F A[2];  
int fun1(int n)
{
    return 0;
}
int fun2(int n)
{
    return A[!!n](n-1) + n;
}

int main()
{
    A[0] = fun1;
    A[1] = fun2;
    cout << A[1](100) << endl;
    cout << A[1](1000) << endl;
    cout << A[1](100) << endl;
    return 0;
}
c. 利用模板类型和枚举类型求解(编译器完成工作)
#include <iostream>
using namespace std;

template<size_t N>class A{
public:
    enum { N = A<N-1>::N + N};
}; 

template<>class A<1>{
public:
    enum { N = 1};
};

int main()
{
    const int n = 100;
    cout << A<n>::N << endl;
    cout << A<500>::N << endl;
/*    cout << A<1000>::T.N << endl;*/  // not support too long like 1000
    return 0;
}

47. 不用 +、-、*、/ 做加法

GO: 奇妙的数学 -> 3.不用加减乘除求两个整数的和

48. 不能被继承的类

有缺陷的方法1:

class A{
public:
    static A* getInstance() { return new A; }
    static void deleteInstance(A *rhs)  { delete[] rhs;}
private:
    A(){}
    ~A(){}
};

缺点:使用麻烦,且只能得到位于堆上的实例。

方法2:利用虚拟继承。

template<typename T>class Help
{
    friend T;
private:
    Help(){}
    ~Help(){}
};
class A : virtual public Help<A>
{
public:
    A(){}
    ~A(){}
};

如上,类 A 可以很方便的声明对象; 同时它是虚拟继承,故若有类继承它,则直接调动 Help 构造函数,导致编译失败。

注: GCC不支持模版参数类型作为友元类型。

posted on 2014-05-04 19:22  进阶之路  阅读(273)  评论(0编辑  收藏  举报