设置多态成员变量的特定参数的通用方法

时间:2013-08-02 09:02:10

标签: c++ oop polymorphism

对于我的问题令人费解的标题感到抱歉,从概念上来说这很简单,但我找不到任何好的设计。

我有一个最终用户可以访问的基类:

class A {
private:
    // m is a functor
    Base* m;
};

class Base {
public:
    virtual void someInterface();
};

class DerivedT1 : public Base {
public:
    virtual void someInterface()
    {
        some_parameter++;
    }
private:
    int some_parameter; // how to set?
};

class DerivedT2 : public Base {
public:
    virtual void someInterface()
    {
        some_other_parameter += a_third_parameter;
    }
private:
    double some_other_parameter; // how to set?
    double a_third_parameter; // how to set?
};

我正在尝试找到从some_parameter的公共接口设置some_other_parameterA的最通用方法。

我想过为我的参数添加一个数字,但这听起来真的丑陋。

有没有漂亮的,面向对象的方式来做到这一点?

3 个答案:

答案 0 :(得分:2)

您想使用A的公共接口来设置派生类参数: 你可以在A中定义一个公共函数,它有一个Base *参数:

class A
{
public:
void setter(const Base *p);
{
     m = p;
}
};

如果要设置Drived1,可以定义Derived1的对象,可以将其传递给setter; 我想你想使用A的公共函数传递值,你必须知道Base*的指针类型,所以你可以通过Derived1Derived2的构造函数传递值!

答案 1 :(得分:1)

我没有其他工作,你总是可以使用动态演员:

DerivedT1 *d1 = dynamic_cast<DerivedT1>(m);
if (d1 != nullptr)
{
    // do something with derived 1
}
else
{
    DerivedT2 *d2 = dynamic_cast<DerivedT2>(m);
    if (d2 != nullptr)
    {
        // do something with derived 2
    }
}

但是如果你需要它,通常表明你的设计有问题。

答案 2 :(得分:0)

如果你想沿着这些方向做点什么

A a; a.setAlgorithmFamily(Algorithm::Type1);
a.getAlgorithmImplementation().setSomeParameter(34);

这是一个快速而又简洁的例子,说明如何做到这一点。 A :: setAlgorithmType基本上是工厂模式,它是最简单的形式。

nclude <iostream>
using namespace std;

class Algorithm {
public:
   virtual void setParameter(int value) = 0;
};
class AlgoX : public Algorithm {
   int mX;
public:
   void setParameter(int value) {
      cout <<"Setting X to " <<value <<endl;
      mX = value;
   }
};
class AlgoY : public Algorithm {
   int mY;
public:
   void setParameter(int value) {
      cout <<"Setting Y to " <<value <<endl;
      mY = value;
   }
};
class A {
public:
   void setAlgorithmType(std::string type) {
      cout <<"Now using algorithm " <<type <<endl;
      if(type == "X")
         mAlgorithm = new AlgoX();
      else if(type == "Y")
         mAlgorithm = new AlgoY();
   }
   Algorithm* getAlgorithmImplementation() { return mAlgorithm; }
private:
   Algorithm* mAlgorithm;
};

int main(int argc, char** argv) {
   A a;
   a.setAlgorithmType("X");
   a.getAlgorithmImplementation()->setParameter(5);
   return 0;
}

这给出了:

Now using algorithm X
Setting X to 5
相关问题