I have something similar to the following structure in my project.

class ProgrammersCacluator {
  public:
    virtual int add(int a, int b);
    virtual int rshift(int a, int b);
}

class MathematiciansCalculator {
  public:
    virtual int add(int a, int b);
    virtual int multiply(int a, int b);
}

I am implementing these as follows:

class ProgrammersCalculatorI : public virtual ProgrammersCalculator {
  public:
    int add(int a, int b);
    int rshift(int a, int b);
}

int ProgrammersCalculatorI::add(int a, int b) {
  return(a + b);
}

int ProgrammersCalculatorI::rshift(int a, int b) {
  return(a >> b);
}

class MathematiciansCalculatorI : public virtual MathematiciansCalculator {
  public:
    int add(int a, int b);
    int multiply(int a, int b);
}

int MathematiciansCalculatorI::add(int a, int b) {
  return(a + b);
}

int MathematiciansCalculatorI::multiply(int a, int b) {
  return(a * b);
}

Now I realize that this is a lot of extra syntax, but the majority of that is enforced by ICE (Internet Communications Engine), which is the framework we are using to communicate between sections of the project.

What I am specifically concerned about is the duplication of the add function. I tried multiple inheritance, but that (obviously) did not work.

Is there a way to adjust the structure of ProgrammersCalculatorI and MathematiciansCalculatorI such that the add method need only be implemented once?

In the actual project add is several hundred lines long and there are several methods like it.

有帮助吗?

解决方案

You would have to make ProgrammersCacluator and MathematiciansCalculator to inherit from same base in slice, something like this:

interface BaseCacluator {
    idempotent int add(int a, int b);
};

interface ProgrammersCacluator extends BaseCalculator {
    idempotent int rshift(int a, int b);
};

interface MathematiciansCalculator extends BaseCalculator {
    idempotent int multiply(int a, int b);
};

Then you can use multiple inheritance to implement add() only once and inherit that implementation:

class BaseCalculatorI : virtual public BaseCalculator {
public:
    virtual int add( int a, int b, const Ice::Current & );
};

class ProgrammersCalculatorI : public BaseCalculatorI, virtual public ProgrammersCalculator {
public:
    virtual int rshift( int a, int b, const Ice::Current & );
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top