Chinaunix首页 | 论坛 | 博客
  • 博客访问: 141197
  • 博文数量: 30
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 300
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-07 10:53
文章分类

全部博文(30)

文章存档

2009年(1)

2008年(29)

我的朋友

分类: C/C++

2008-05-20 10:05:43

重载overload和重写override均是多态的一种!
虚函数属于重写的范畴!
但是,如果重载了虚函数会怎样呢?
 

#include <iostream>
#include <string>
#include <memory>

#define str(f) #f

void printLine(std::string s)
{
    std::cout<<s<<std::endl;
}

class A
{
public:
    virtual void vfun(int) { printLine(str(vfun in A)); }
    void fun(int) { printLine(str(fun in A)); }
};

class B : public A
{
public:
    void vfun(double) { printLine(str(vfun in B));}
};

int main()
{
    std::auto_ptr<A> pb(new B);
    pb->fun(1);
    pb->vfun(1.0); // 1 warning

    pb->vfun(1);
    system("pause");
    return 0;
}

输出结果:

fun in A
vfun in A
vfun in A

可见,如果通过指向基类的指针,而该指针实际指向一个子类,调用虚函数时,而子类重载了该虚函数,则实际调用的仍是基类中的虚函数。(自顶向下,基类隐藏了子类)

修改一下上面的main函数:

int main()
{
    std::auto_ptr<B> pb(new B);
    pb->fun(1);
    pb->vfun(1.0);
    pb->vfun(1);
    system("pause");
    return 0;
}

输出结果:

fun in A
vfun in B
vfun in B

可见,如果通过指向子类的指针,调用虚函数,而子类重载了该虚函数,则实际调用的将是子类中的虚函数。(自下向上,子类隐藏了基类的虚函数)

即使子类重载了基类中的虚函数,还是可以让基类中虚函数在子类中存在的:

#include <iostream>
#include <string>
#include <memory>

#define str(f) #f

void printLine(std::string s)
{
    std::cout<<s<<std::endl;
}

class A
{
public:
    virtual void vfun(int) { printLine(str(vfun in A)); }
    void fun(int) { printLine(str(fun in A)); }
};

class B : public A
{
public:
    using A::vfun; // newly added

    void vfun(double) { printLine(str(vfun in B));}
};

int main()
{
    std::auto_ptr<B> pb(new B);
    pb->fun(1);
    pb->vfun(1.0);
    pb->vfun(1);
    system("pause");
    return 0;
}

输出结果:

fun in A
vfun in B
vfun in A

阅读(904) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-09-10 23:40:32

3Q

chinaunix网友2008-09-10 23:40:28

3Q