mardi 3 avril 2018

Strategy pattern on C++

I'm trying porterd example of Strategy pattern from HeadFirst book from java to C++

#include "iostream" using namespace std;
class IFlyBehavior
{
public:
    virtual void fly() = 0;
};

class FlyWithWings : public IFlyBehavior
{
public:
    void fly() override
    {
        cout << "fly!";
    }
};
class FlyNoWay : public IFlyBehavior
{
public:
    void fly() override
    {
        cout << "no fly!";
    }
};

class IQuackBehavior
{
public:
    virtual void quack() = 0;
};
class Quack : public IQuackBehavior
{
public:
    void quack() override
    {
        cout << "Quack!";
    }
};
class Squeak : public IQuackBehavior
{
public:
    void quack() override
    {
        cout << "Squeak!";
    }
};
class MuteQuack : public IQuackBehavior
{
public:
    void quack() override
    {
        cout << "Can't quack";
    }
};

class Duck : public IFlyBehavior, IQuackBehavior
{
public:
    FlyWithWings* fly_behavior;
    Quack* quack_behavior;
    void swim()
    {
        cout << "Swim!";
    }
    virtual void display() = 0;
    void performQuack()
    {
        quack_behavior->quack();
    }
    void performFly()
    {
        fly_behavior->fly();
    }
};

class MallardDuck : public Duck
{
public:
    MallardDuck()
    {
        quack_behavior = new Quack();
        fly_behavior = new FlyWithWings();
    }

    void display() override
    {
        cout << "Mallard!";
    }
};
class RedheadDuck : public Duck
{
public:
    void display() override
    {
        cout << "RedHead!";
    }
};
class DecoyDuck : public Duck
{
public:
    void display() override
    {
        cout << "DecoyDuck!";
    }
};
class RubberDuck : Duck
{
public:
    void display() override
    {
        cout << "RubberDuck!";
    }
};


int main(int argc, char* argv[])
{
    Duck* md = new MallardDuck;
    md->performFly();
    md->performFly();
    return 0;
}

But i got error: E0322 object of abstract class type "MallardDuck" is not allowed: Duck d:\Code\CODE\C++\Duck\Duck\Source.cpp 119 It's seems like compiler not see realized classes, why this happen? Any ideas about it? How I must do?

Aucun commentaire:

Enregistrer un commentaire