【问题标题】:base class constructor won't call derivied class version of virtual method [duplicate]基类构造函数不会调用虚拟方法的派生类版本[重复]
【发布时间】:2012-07-03 17:18:38
【问题描述】:

可能重复:
Calling virtual function of derived class from base class constructor?

我有以下文件(请原谅拼写错误,我从内存中快速重写代码)

BaseReader(){
    openFile();
}

void BaseReader::openFile(){
    //logic to open file
}

打开文件在 .h 中被声明为虚拟公共方法(它受到保护,但我在试图找出问题所在时将其切换为公共方法)。 SortReader 定义为:

class SortReader: public BaseReader{
    public:
            SortReader();
            void openFile();
    };

使用以下代码:

SortReader::SortReader(): BaseReader(){}

SortReader::openFile(){
    sortFile();
    BaseReader::openFile();
}

当我尝试构造一个 SortReader 对象时,永远不会调用 sortFile 方法。我可以在调试器中遍历它并观察 SortReader 调用 BaseReader 构造函数 BaseReader 构造函数调用 openFile,后者调用 openFile 的 BaseReader 版本。我希望它调用 SortReader 的打开文件的实现。我需要做什么才能让这种情况发生?

【问题讨论】:

  • 显然问题是openFile() 没有被声明为虚拟...
  • @RichardJ.RossIII:根据问题,虽然没有看到声明我们不能完全确定。但不管是不是,都不能从基类构造函数中调用派生类版本。

标签: c++ constructor polymorphism


【解决方案1】:

你不能。在构造函数完成之前,对象还没有完全构造。一般来说,从构造函数调用virtual 方法是个坏主意。

您可以将逻辑委托给单独的非virtual 方法:

SortReader::openFile(){
    sortFileInternal();     //not virtual
                            //defined in SortReader
    BaseReader::openFile();
}

SortReader::sortFile()      //the virtual method
{
    sortFileInternal();
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-09-27
  • 2021-05-09
  • 2019-04-19
  • 2011-03-05
  • 2016-07-19
  • 1970-01-01
  • 2011-05-03
  • 2018-07-16
相关资源
最近更新 更多