小编以前学过java,知道java支持子类对象访问父类的重载函数.不过到了c++,好像不是那么回事了.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;
class canidae
{
public:
void call()
{
cout<<"this is is canidae animal"<<endl;
}
};
class fox:canidae
{
public:
void call(string str)
{
cout<<"this is a "<<str<<" fox"<<endl;
}
};
int main()
{
fox fox1;
fox1.call("sly");
//错误
fox.call();
return 0;
}

Error

1
2
3
4
5
6
7
8
9
test.cpp: In function ‘int main()’:
test.cpp:43:15: error: no matching function for call to ‘fox::call()’
fox1.call();
^
test.cpp:43:15: note: candidate is:
test.cpp:34:10: note: void fox::call(std::string)
void call(string str)
^
test.cpp:34:10: note: candidate expects 1 argument, 0 provided

Analysis

错误提示:fox1没有call()函数,可以候选的是call(string str)函数
那就怪了,我们不是继承了canidae类吗?它里面有不带参数的call()函数
原因是c++不支持继承中的重载

1
fox1.canidae::call();

替换

1
fox1.call();

即可访问父类的重载函数.

Summary

相比java等面向对象语言,c++对类的管控更加严格.