如何创建C ++类以基于不同的类似类执行相同的计算?

时间:2014-07-06 23:29:14

标签: c++ class inheritance

可能我的标题有点含糊不清,因为我不确切地知道它是如何被称为我希望实现的(所以欢迎你建议改进标题)。但是,请查看以下代码示例。

我有一些类似的类(aSumSub,bSumSub,... xSumSub)。实际上,它们具有完全相同的变量和功能,但它们以不同的方式实现。

我想创建另一个类(SumSub),它将根据这些xSumSub类中的任何一个进行一些计算。执行这些额外计算的函数是results1,results2 .. etc。

如何以有效的方式实现这一目标?最简单的方法是复制SumSub类,给它一个不同的名称,然后简单地改变变量的类型" x"和构造函数。但是,这需要我一遍又一遍地复制几百行代码,只是为了改变几行,使其与所有xSumSub函数兼容。

必须有一个更清洁的方式!

#include <iostream>

using namespace std;

// Class a
// I am not allowed to modify this
class aSumSub {
public:   
   int sum(){
    return 10+1;
   }

   int sub(){
    return 10-1;
   }
};

// Class b which has EXACTLY the same types of functions and variables as Class a has, but it's different implementation.
// I am not allowed to modify this
class bSumSub {
public:   
   int sum(){
    return 20+1;
   }

   int sub(){
    return 20-1;
   }
};

// Here we could have class cSumSub, ..... xSumSub etc.
// Not allowed to modify either.


// The following Class SumSub is doing some calculations that they are based on the output of the functions of the xSumSub classes.
// That's the one I want to create
class SumSub {
public:
   bSumSub *x; // <- How can I make this variable to be either of type bSumSub or aSumSub or xSumSub?

   SumSub(bSumSub *ssclass){ // And consequently, how can I have the constructor accepting either bSumSub or a aSumSub or xSumSub?
    x = ssclass;
   }

   // The rest of the functions should't need any modification
   // because we know that *x will always have the same functions and the same types will always be returned.
   void result1(){
    cout << x->sum() << endl;
   }

   void result2(){
    cout << x->sub() << endl;
   }

   void result3(){
    cout << x->sum()-x->sub() << endl;
   }

   void result4(){
    cout << x->sum()+x->sub() << endl;
   }


};

int main(){
   aSumSub as;
   bSumSub bs;

   cout << "as.sum=" << as.sum() << endl;
   cout << "bs.sum=" << bs.sum() << endl;

   SumSub ss1(&bs);
   cout << endl << "SumSub" << endl;
   ss1.result1();
   ss1.result2();
   ss1.result3();
   ss1.result4();

   // I would like to be able to do the following as well
   //SumSub ss2(&as);
   //cout << endl << "SumSub" << endl;
   //ss2.result();
   //ss2.result1();
   //ss2.result2();
   //ss2.result3();
   //ss2.result4();

   return 0;
}

2 个答案:

答案 0 :(得分:3)

使用模板。这是模板SumSub

template <typename T> class SumSub {
public:
   T *x;

   SumSub(T *ssclass){
    x = ssclass;
   }

   void result1(){
    cout << x->sum() << endl;
   }

   void result2(){
    cout << x->sub() << endl;
   }

   void result3(){
    cout << x->sum()-x->sub() << endl;
   }

   void result4(){
    cout << x->sum()+x->sub() << endl;
   }


};

答案 1 :(得分:2)

使用模板:

template <typename BumStub>
struct SumSub
{
    using type = BumStub;

    type * x;

    SumSub(type * p) : x(p) { }

    void result1() { std::cout << x->sum() << std::endl; }

    // etc.
}

用法:

aSumSub as;
SumSub<aSumSub> ss1(&as);
ss1.result1();