开发者

What good is virtual in a class? [duplicate]

This question already has answers here: 开发者_开发技巧 Closed 12 years ago.

Possible Duplicate:

C++ Virtual/Pure Virtual Explained

For example i have:

class A {
    private: 
        int i; 
        int j; 

    public: 
        void k (int l, int m) { i=l; j=m; } 
        virtual int n (void); 
};

class B : public A { 
    public: 
        int n (void);
};

What good is this virtual ?


I like to use the Chess Game as an example for this:

class ChessPiece
{
    public:
       virtual int Move() = 0;
};
class Queen: public ChessPiece
{
    public:
       virtual int Move() { /* STUFF */ }
};

bool AICode()
{
    int bestMove = 0;
    foreach(ChessPiece* loop = board.Pieces().begin(); loop != board.Pieces().end(); ++loop)
    {
        bestMove = max(bestMove, loop->Move());
    }
 }

The AICode() does not need to know which piece it is looking at.
All it does is ask the piece to see what its best move is. The virtual dispatch mechanism will work out the type of piece and call the correct Move() method.


It's to induce polymorphic behaviour, which means that a single contract can be used by a client to invoke different behaviours, without the client having to know about every possible behaviour.

A* a = new B();
a->n(); // Will call B::n();

As a more concrete example, here some fairly stereotypical code:

struct Shape {
    GLfloat transform_[4][4];

    void render() const {
        glPushMatrix();
        glMultMatrixf(&transform_[0][0]);
        draw();
        glPopMatrix();
    }

    virtual void draw() const = 0;
};

struct Line : public Shape {
    GLfloat x1, y1, x2, y2;

    void draw() {
        glBegin();
        glVertex2f(x1, y1);
        glVertex2f(x2, y2);
        glEnd();
    }
};

struct Square : public Shape {
    GLfloat size;

    void draw() {
        GLfloat f = size/2;
        glBegin();
        glVertex2f(-f, -f);
        glVertex2f( f, -f);
        glVertex2f( f,  f);
        glVertex2f(-f,  f);
        glVertex2f(-f, -f);
        glEnd();
    }
};

void renderShapes(Shape* shapes, int nShapes) {
    for (int i = 0; i < nShapes; ++i) {
        shapes[i]->render();
    }
}

(Disclaimer: The above code is neither correct nor complete, and is certainly not to be held up as an example of good graphics code. It's just to illustrate when virtual functions are useful.


I refer you to this excellent SO page about polymorphism.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜