在C++中有三个很相似的概念,很容易混淆。
下面就来总结区分,下面是测试代码
不过在分析代码之前先来分析一下关于上面的三个名词的概念
重载:1)必须在同一个类中,2)函数名相同,参数列表不同;
重写:1)必须发生在父子类中,2)函数名声明完全一致,且在父类中必须是虚函数;
重定义:1)必须发生在父子类中,2)函数名相同,且在父类中不是虚函数;
以上三个定义应该很好理解[个人总结,如有错误,请自行区分]
#include <iostream>
using namespace std;
class A
{
public:
void print(){cout << "this A\n";}
virtual void print(int a){cout << "test A" << a;}
};
class B:public A
{
public:
void print(int a,int b){cout << "this B" << a << b;}
virtual void print(int b){cout << "test B" << b;}
};
关于如何编写测试用例,请根据上面的概念自行编写,这里我主要相对重定义进行一下测试。
c
int main(void)
{
A aa;
B bb;
bb.print();
}
编译结果:
test.cpp: In function ‘int main()’:
test.cpp:21:11: error: no matching function for call to ‘B::print()’
bb.print();
^
test.cpp:21:11: note: candidates are:
test.cpp:13:7: note: void B::print(int, int)
void print(int a,int b){cout << "this B" << a << b;}
^
test.cpp:13:7: note: candidate expects 2 arguments, 0 provided
test.cpp:14:15: note: virtual void B::print(int)
virtual void print(int b){cout << "test B" << b;}
^
test.cpp:14:15: note: candidate expects 1 argument, 0 provided
可以看出子类不可以调用从父类那里继承过来的同名函数,这是因为子类覆盖了父类的函数名。如果此时一定要调用父类的同名方法必须要加上域名运算符::.
bb.A::print();即可。