C++ 为什么这个程序挂起?

C++ 为什么这个程序挂起?,c++,inheritance,C++,Inheritance,我有以下代码,这似乎是导致无限循环: struct X { void my_func( int ) { std::cout << "Converted to int" << std::endl; } }; struct X2 : X { void my_func( char value ) { my_func(value); } }; struct X { void my_func(int){std::cout第二位是无限递归的: struct X2 : X

我有以下代码,这似乎是导致无限循环:

struct X
{
  void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};

struct X2 : X
{
  void my_func( char value ) { my_func(value); }
};
struct X
{

void my_func(int){std::cout第二位是无限递归的:

struct X2 : X
{
  void my_func( char value ) { my_func(value); } //calls itself over and over again
};
my_func
前面加上基类的名称,就可以了

struct X2 : X
{
  void my_func( char value ) { X::my_func(value); }
};
< > >强>编辑<强>刚刚意识到基类<代码> MyuFunc 的签名是不同的。C++编译器静态地解决函数的超载,这意味着它将选择与参数类型匹配的函数,这就是为什么它调用<代码> char < /Cult>过载> < /P> 例如:

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
char-cChar='a';
myfunc(cChar);
void myfunc(char a){}//
您正在传递
,它是
char
,因此它决定使用接受
char
参数调用相同的方法。它将成为一个无休止的循环

void my_func( char value ) { my_func(value); }

在这里,你编写了一个没有基本情况的递归函数。我对C++的了解不多,但是你需要指定你想调用X的MyyFunc,而不是X2(我假设这就是你想要做的)。


编辑:若要修复它,您需要将值强制转换为int

程序进入无限循环。my_func()调用自身,并且没有退出的条件。

您的调用my_func(值)是递归的。您是指super::my_func(值)吗?

问题是由于隐藏而发生的。

您需要显式调用基类的函数,即:

struct X
{
  void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};

struct X2 : X
{
  void my_func( char value ) { X:my_func(value); }
};
struct X
{

作废我的函数(int){std::cout Thanx。我当时以为
my_func
还没有定义,应该调用
X::my_func
。@zilgo:它没有定义,但是声明了。这就是你所需要的。在派生类中,任何同名但签名不同的函数都会隐藏同名的基类函数。这意味着在
X2
的成员函数中,unqualified
my_func
总是指
X2::my_func
,而从不指
X::my_func
。这里没有“最佳匹配”。发布的“例如:是误导性的,因为它根本不适用于这种情况。@Charles Bailey。谢谢。更正。这里没有程序,只有两个类定义。它不挂起,也不能挂起。事实上,它不能运行。发布您试图运行的真实代码。我们大多数人都能够填补空白。只需说:“…@Igor Zevaka:当然。但10个案例中有9个是这样的“填空"对一个毫无意义的问题产生了一个无用的答案。我希望这个答案在起作用时能被证明是十分之一。将参数转换为
int
不会有任何帮助。
my_func
在派生类中隐藏了基类
my_func
。需要明确限定
my_func
。它不是过载了吗我们不能隐藏它吗?
struct X
{
  void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};

struct X2 : X
{
  void my_func( char value ) { X:my_func(value); }
};