一堂课虚拟有什么用?

时间:2010-08-25 23:29:38

标签: c++ oop virtual

  

可能重复:
  C++ Virtual/Pure Virtual Explained

例如我有:

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);
};

这个虚拟有什么用?

3 个答案:

答案 0 :(得分:2)

这是为了诱导多态行为,这意味着客户可以使用单个合同来调用不同的行为,而客户不必知道每个可能的行为。

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

作为一个更具体的例子,这里有一些相当陈规定型的代码:

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();
    }
}

(免责声明:上述代码既不正确也不完整,当然不能作为良好图形代码的例子。它只是说明虚函数何时有用。

答案 1 :(得分:2)

我喜欢以国际象棋游戏为例:

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());
    }
 }

AICode()不需要知道它正在看哪一块 所有这一切都要求这件作品看看它的最佳动作是什么。虚拟调度机制将计算出片段的类型并调用正确的Move()方法。

答案 2 :(得分:1)

我建议你参考这个关于polymorphism的优秀SO页面。

相关问题