继承,定义用于创建指定类型的对象的函数?

时间:2014-03-15 22:34:23

标签: c++ inheritance

标题无济于事。

无论如何,目前我正在使用以下

http://puu.sh/7wJed.png

然而,为了创造一个说“飞机载体”的对象,一切都很好并且正确地继承了。我需要每次都传递12个值+两个继承的值,我想使用一个函数,如

generateAirCraftCarrier(1,2,3,4,5,6,7,8,9,10,11,12);

我可以简单地将一个navalVessel实例传入函数,例如

generateAirCraftCarrier(myNavalVessel, inherit var 1, inherit var 2);

但这并不完全是一个解决方案,因为当航空母舰有一个不同的“速度”时会发生什么?例如?

我可以使用选项参数,如果为null,则使用myNavalVessel对象吗?在这里寻找一些指导,对于胡言乱语感到遗憾。

2 个答案:

答案 0 :(得分:1)

为什么你需要一个函数来定义AircraftCarrier上的所有12个值?为什么不在AircraftCarrier和NavalVessel上建立一些游戏机呢? e.g:

class NavalVessel {
  float speed_;

public:
  void setSpeed(float speed) { speed_ = speed; }
};

class AircraftCarrier : public NavalVessel {
  int noHeliPads_;
  int noRunways_;

public:
  void setNoHeliPads(int noHeliPads) { noHeliPads_ = noHeliPads; }
  void setNoRunways(int noRunways) { noRunways_ = noRunways; } 
};


int main() {
    AircraftCarrier aircraftCarrier;
    aircraftCarrier.setSpeed(25.3);
    aircraftCarrier.setNoHeliPads(3);
    aircraftCarrier.setNoRunways(2);
}

答案 1 :(得分:0)

命名参数成语对您有用吗?

class AircraftCarrierParameters;

class AircraftCarrier
{
private:
    AircraftCarrierParameters _params;
public:
    AircraftCarrier(const AircraftCarrierParameters& params)
        : _params(params) {}
    AircraftCarrierParameters params() const { return _params;}
};

class AircraftCarrierParameters
{
private:
    double _speed;
    int _someOtherStuff;

public:
    AircraftCarrierParameters()
        : _speed(0)             //default parameters
        , _someOtherStuff(0)
    {

    }
    double speed() const { return _speed; }
    double someOtherStuff() const { return _someOtherStuff; }

    AircraftCarrierParameters& setSpeed(double speed) { _speed = speed; return *this; }
    AircraftCarrierParameters& setSomeOtherStuff(double stuff) { _someOtherStuff = stuff; return *this; }
};

AirCraftCarrier generateAirCraftCarrier(const AircraftCarrierParameters& params)
{
    //...
}

void main()
{
    AircraftCarrier c1(AircraftCarrierParameters());
    AircraftCarrier c2(c1.params().setSpeed(30));
}