覆盖C ++

时间:2010-02-05 02:33:28

标签: c++ oop

class base {  
    public: 
        int foo();  
        int foo(int a);  
        int foo(char* b);    
        int doSomething(int);    
 }

 class derived : public base
  { 
  public: 
     int doSomething(int b); 
  }

 int derived::doSomething( int b) 
   {
     base::doSomething(b);  
       //Make Something else 
   }

 int main() 
 { 
     derived d= new derived();  
     d->foo();
 }

现在在foo方法(其中任何一个)中我想调用更具体的doSomething。如果我实例派生类我想要派生类的doSomething,并且如果我实例基类我想要基类的doSomething,尽管我正在调用基类中实现的foo方法。

int base::foo()
{
 //do something
 makeSomething(5);
}

3 个答案:

答案 0 :(得分:3)

在基类中,将doSomething方法设为虚拟:

public:

virtual int doSomething(int);

然后你可以:

Base* deriv = new Derived();

Base* base  = new Base();

deriv->doSomething();
base->doSomething();

享受!

答案 1 :(得分:2)

这就是虚函数的用途:

struct A {
    virtual ~A() {}
    virtual void f() {}
};

struct B : A {
    void f() {}
};

// ...
A* a = new A;
A* b = new B;
a->f(); // calls A::f
b->f(); // calls B::f

C ++ FAQ lite covers some details,但无法取代好introductory book

答案 2 :(得分:0)

我建议这个例子来说明使用虚拟或不使用

之间的区别
struct A {
    virtual ~A() {}
    virtual void f() {}
    void g() {}
};

struct B : A {
    void f() {}
    void g() {}
};

A* a = new A;
A* b = new B;
a->f(); // calls A::f
b->f(); // calls B::f
b->g(); // calls A::g