代码之家  ›  专栏  ›  技术社区  ›  big-z

为什么这个程序挂起?

  •  4
  • big-z  · 技术社区  · 14 年前

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

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

    它有什么问题?

    7 回复  |  直到 14 年前
        1
  •  10
  •   Igor Zevaka    14 年前

    第二位无限递归:

    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); }
    };
    

    编辑 刚刚意识到基础阶级 米奥芬克 的签名不同。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
    

    谢谢查尔斯·贝利。在这种情况下,上述代码不适用于 X2 米奥芬克 隐藏基类 米奥芬克 . 这就留下了唯一一个用类名限定函数的解决方案。

        2
  •  2
  •   user151323    14 年前
    void my_func( char value ) { my_func(value); }
    

    你通过了 value 哪个是 char 因此,它解析为使用接受 烧焦 参数。它变成了一个无止境的循环。

        3
  •  2
  •   Bwmat    14 年前
    void my_func( char value ) { my_func(value); }
    

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

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

        4
  •  0
  •   Kevin Le - Khnle    14 年前

    程序进入无限循环。我的_func()调用自己,没有条件退出它。

        5
  •  0
  •   Eyal Schneider    14 年前

    您的调用my_func(value)是递归的。你的意思是“超级”:“我的价值”?

        6
  •  0
  •   Raam    14 年前
        7
  •  0
  •   Mephane    14 年前

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

    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); }
    };
    

    默认情况下,编译器使用同一类中的函数(如果存在),因为它无法知道您实际要使用哪个函数。通过指定 BaseClass::Function 在派生类的方法中,编译器将显式创建对该基类方法的调用,即使您已重写。