c++ 关于继承 关于虚函数解决办法

c++ 关于继承 关于虚函数
C/C++ code

class Base
{
   Base();
   ~Base();
   virtual foo(){cout<<"Base::foo"<<endl;}
}

class Derive :public Base
{
    Derive(){foo();};
    ~Derive();
    foo(){cout<<"Derive::foo"<<endl;
}

void main()
{
   Derive b;
}




 代码大致这样 大家领会一下精神吧 输出的结果是先调用了 base的foo 然后调用了 derive的foo 为啥呢 为什么会调用2次?

------解决方案--------------------
楼主给出的代码,不可能会调用两次foo的。你是不是想这样写:
C/C++ code

#include <iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        foo();      // 这里也增加一个调用
    }

    virtual ~Base(){}
    virtual void foo()
    {
        cout << "Base::foo" << endl;
    }
};

class Derive :public Base
{
public:
    Derive()
    {
        foo();
    }
    ~Derive(){}
    void foo()
    {
        cout << "Derive::foo" << endl;
    }
};

int main(int argc, char* argv[])
{
    Derive b;
    return 0;
}