【发布时间】:2013-09-18 09:55:04
【问题描述】:
这是我尝试过的(“有趣”的功能必须是静态的):
#include<iostream>
class A
{
public:
static void fun(double x) { std::cout << "double" << std::endl; }
};
class B
{
public:
static void fun(int y) { std::cout << "int" << std::endl; }
};
class C
:
public A,
public B
{
};
int main(int argc, const char *argv[])
{
double x = 1;
int y = 1;
C::fun(x);
C::fun(y);
return 0;
}
并使用 g++ (GCC) 4.8.1 20130725 (prerelease),我得到以下错误:
main.cpp: In function 'int main(int, const char**)':
main.cpp:27:5: error: reference to 'fun' is ambiguous
C::fun(x);
^
main.cpp:12:21: note: candidates are: static void B::fun(int)
static void fun(int y) { std::cout << "int" << std::endl; }
^
main.cpp:6:21: note: static void A::fun(double)
static void fun(double x) { std::cout << "double" << std::endl;
所以我的问题是:如果我可以覆盖 member functions 而不是静态函数,那么 C++ 怎么来?为什么在这种情况下重载不起作用?我希望编译器将“有趣”带入命名空间 C::,然后进行名称修改并使用重载来区分 C::fun(int) 和 C::fun(double)。
【问题讨论】:
-
这不是因为函数是静态的,而是因为你的类层次结构。去掉'static'关键字,就没有区别了。
-
@SingerOfTheFall:它们必须是静态的,没有机会让它们成为成员函数,我正在处理遗留代码。
-
@tomislav-maric:当函数不是静态的时,歧义不会消失。
-
@tomislav-maric,我明白了,我只是说
static的功能不是问题的根源 -
名称查找后发生重载解析。编译器在
C中找不到fun,因此它在两个基类中查找名称并找到两个不明确的fun。
标签: c++ inheritance static-methods