本博客(
http://blog.csdn.net/livelylittlefish
)贴出作者(三二一、小鱼)相关研究、学习内容所做的笔记,欢迎广大朋友指正!
虚函数与重载函数的区别
重载函数在类型和参数数量上一定不相同,而重定义的虚函数则要求参数的类型和个数、函数返回类型相同;
虚函数必须是类的成员函数,重载的函数则不一定是这样;
构造函数可以重载,但不能是虚函数,析构函数可以是虚函数。
虚函数必须是类的成员函数,重载的函数则不一定是这样;
构造函数可以重载,但不能是虚函数,析构函数可以是虚函数。
例1:
#include
<
iostream.h
>
class
CBase
...
{
public:
virtual int func(unsigned char ch) ...{return --ch;}
}
;
class
CDerive :
public
CBase
...
{
int func(char ch) ...{return ++ch;} //此为函数重载
}
;
void
main()
...
{ CBase *p=new CDerive;
int n=p->func(40); //调用基类的 func()
cout<<" the result is : "<<n<<endl;
}
运行结果:
the result is : 39
例2:
#include
<
iostream.h
>
class
CBase
...
{
public:
virtual int func(unsigned char ch) ...{return --ch;}
}
;
class
CDerive :
public
CBase
...
{
int func(unsigned char ch) ...{return ++ch;} //此为虚函数
}
;
void
main()
...
{ CBase *p=new CDerive;
int n=p->func(40); //调用派生类的 func()
cout<<" the result is : "<<n<<endl;
}
运行结果:
the result is : 41
本文探讨C++中的虚函数与重载函数,通过两个实例分析它们在多态性和调用机制上的关键差异。
——虚函数与重载函数的区别&spm=1001.2101.3001.5002&articleId=2171515&d=1&t=3&u=e7c39a96cf1b425b952a6548bf09c34a)
4649

被折叠的 条评论
为什么被折叠?



