/*
* 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成功!