【问题标题】:Subclass recursive method call子类递归方法调用
【发布时间】:2011-09-19 23:47:19
【问题描述】:

在我的 FileProc 类中,我有四个函数:

ReadFile(TemplateList<char> &ReadList){}
ReadFile(TemplateListAdv<char> &ReadList){}
ReadFile(CharList &ReadList){}
ReadFile(CharListAdv &ReadList){}

它们都应该调用集中式方法(它们被转换为):

ReadFile(TemplateListEditor<char> &ReadList){} //Contained by FileBasic

关于背景信息,类层次结构如下:

模板列表 -> 字符列表
模板列表 -> 模板列表Adv
CharList -> CharListAdv
模板列表 -> 模板列表编辑器
FileBasic -> FileProc

我的问题是有一个递归函数调用(其中 TemplateList 转换为 TemplateListEditor 将继续调用 TemplateList 函数),尽管类在内部是不同的。类型转换似乎不起作用。如果不重命名函数(这会破坏它应该是通用的),我如何让方法查找正确的方法?

(我很惊讶编译器从未为此标记出歧义解决错误)。

例子:

const bool ReadFile(TL::TemplateList<char> &ReadList, const bool Recursion = false)
{
    printf("Is recursion true? %d!\n",Recursion);
    TL::TemplateListEditor<char> Temp(ReadList);

    //Calls itself instead of
    //const bool ReadFile(TL::TemplateListEditor<char> &ReadList, const bool Recursion = false)
    if(!ReadFile(static_cast<TL::TemplateListEditor<char> &>(Temp),true ))
    {
        return false;
    }
    return true;
}

上面会输出:

递归是真的吗? 0
递归是真的吗? 1
递归是真的吗? 1
等等

令我震惊的是 TemplateListEditor(尽管是静态转换等)不知何故或出于某种令人难以置信的原因,被转换回 TemplateList。编辑器的构造函数都是显式的。

【问题讨论】:

  • 你能给出一个实际的代码示例来说明你的意思吗?
  • 它是嵌入式的,有点困难。我会尽力。但基本上,编译器以某种方式将 TemplateListEditor 翻译回 TemplateList ......啊哈......复制构造函数不是显式的......我希望它们不是......(对不起,它们是显式的。同样的问题。 )

标签: c++ class methods recursion subclass


【解决方案1】:

你的问题不是很清楚。但我假设你有这样的东西:

class A { ... };
class B : public A { ... };

void readFile(A &a) { ... };

void readFile(B &b)
{
    readFile(b); // Recursive call
    readFile(static_cast<A&>(b));  // Non-recursive call
}

函数重载是在编译时确定的,而不是在运行时确定的。编译器尝试根据参数的 static 类型定位最佳匹配。

【讨论】:

  • 谢谢。这就是我的意思。我试图制作示例代码,但它的行为不像 FileProc 类中的问题。但这就是我的意思。是的。谢谢。
  • 基本上,B 被传递给一个期望 B 的函数,但是 B 被转换为 A,它调用将 A 转换为 B 的 A 函数,因此它可以调用 B 函数(循环返回本身)。转换是隐式的,所以我不知道如何让它正确地进行。 Arrgggh 压力。
  • 抱歉 Oli,static_cast(如 typecast)对我不起作用。它仍在将 TemplateListEditor 转换为 TemplateList。
猜你喜欢
  • 2023-04-10
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 2021-11-07
  • 2016-03-02
  • 2013-02-17
相关资源
最近更新 更多