我有以下代码似乎导致无限循环:
struct X
{
void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};
struct X2 : X
{
void my_func( char value ) { my_func(value); }
};
Run Code Online (Sandbox Code Playgroud)
它有什么问题?
Igo*_*aka 10
第二位是无限递归的:
struct X2 : X
{
void my_func( char value ) { my_func(value); } //calls itself over and over again
};
Run Code Online (Sandbox Code Playgroud)
前缀my_func与基类的名称,你会没事的
struct X2 : X
{
void my_func( char value ) { X::my_func(value); }
};
Run Code Online (Sandbox Code Playgroud)
编辑刚才意识到基类my_func的签名是不同的.C++编译器静态地解析函数重载,这意味着它将选择最适合参数类型的函数,这就是它调用char重载的原因.
例如:
char cChar = 'a';
myfunc(cChar);
void myfunc(char a){} //<-- this one is called
void myfunc(int a){}
int iInt = 1;
myfunc(iInt);
void myfunc(char a){}
void myfunc(int a){} //<-- this one is called
Run Code Online (Sandbox Code Playgroud)
谢谢Charles Bailey.如上面的代码不会在这种情况下应用X2的my_func隐藏基类的my_func.这留下了使用类名限定函数的唯一解决方案.