c++ - 基类构造函数不会调用派生类版本的虚方法

标签 c++ constructor polymorphism

<分区>

Possible Duplicate:
Calling virtual function of derived class from base class constructor?

我有以下文件(请原谅打字错误,我根据内存快速重写了代码)

BaseReader(){
    openFile();
}

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

打开文件在 .h 中被声明为虚拟公共(public)方法(它受到保护,但我在试图找出问题所在时将其切换为公共(public)方法)。 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 对打开文件的实现。我需要做什么才能做到这一点?

最佳答案

你不能。在构造函数完成之前,对象尚未完全构造。通常,从构造函数调用 virtual 方法不是一个好主意。

您可以将逻辑委托(delegate)给一个单独的非虚拟方法:

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

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

关于c++ - 基类构造函数不会调用派生类版本的虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11315939/

相关文章:

c++ - 致命的Python错误: Couldn't create autoTLSkey mapping with C++ binding

c++ - 如何在 C++ 中有效地读取新行分隔的整数?

c++ - 检查预处理器中的 __declspec 宏

c++ - 包含带有模板对象的容器的类

java - 类型不匹配 : cannot convert from Map<String, List<Animal>> 到 Map<String,List<Dog>>

Rust 在专用版本中调用函数的默认实现

c++ - 对于无效的 QModelIndex,重载的 QAbstractItemModel::flags 应该返回什么?

c++ - 为什么不能在 C++ 中将构造函数声明为静态的?

c++ - 在 C++ 构造函数中使用自动变量

c++ - C++中构造函数如何选择基类构造函数