C++中Override的两个例子

/*
 * main.cc
 *
 *  Created on: 2008-8-5
 *      Author: Administrator
 */
#include <iostream>
 
class Base
{
public:
    virtual Base *clone(){ std::cout << "Base::clone() \n"; return new Base;}
};
 
class Derived : public Base
{
public:
    Derived *clone(){ std::cout << "Derived::clone() \n"; return new Derived;}
};
 
int main(int arg, char **args)
{
    Derived *pd = new Derived;
    pd->clone();
 
    Base *pb = pd;
    pb->clone();
 
    return 0;
}

结果:

Derived::clone()
Derived::clone()

可以看到,虽然返回类型不完全相同,但是父类中返回值是一个指针或引用,子类override时可以返回这个指针(或引用)的派生,可见这种情况下,override成功了

再看下例:

 
#include <iostream>
 
class Base
{
public:
    virtual Base *clone(){ std::cout << "Base::clone() \n"; return new Base;}
    virtual void copy(Base&){ std::cout << "Base::copy() \n"; }
};
 
class Derived : public Base
{
public:
    Derived *clone(){ std::cout << "Derived::clone() \n"; return new Derived;}
    void copy(Derived&) { std::cout << "Derived::copy() \n"; }
};
 
int main(int arg, char **args)
{
    Derived d;
    Base b;
 
    Derived *pd = new Derived;
    pd->copy(d);
 
    Base *pb = pd;
    pb->copy(b);
 
    return 0;
}

结果:

Derived::copy()
Base::copy()

可见这种情况下,override并没有发生,hide发生了

void copy(Derived&) { std::cout << "Derived::copy() \n"; }

改为:

void copy(Base&) { std::cout << "Derived::copy() \n"; }
则可以override成功!
posted @ 2008-08-05 18:01  中土  阅读(8620)  评论(2编辑  收藏  举报
©2005-2008 Suprasoft Inc., All right reserved.