繁体   English   中英

C ++:在非虚函数中使用纯虚函数

[英]C++: use a pure virtual function in a non-virtual function

我正在尝试创建一个基类,为所有派生类定义接口。

我想有一个函数,允许该类读取该类的配置文件,使用boost::property_tree 我们将此函数称为readConfig 这必须在每个派生类中定义,因此我将其设为纯虚拟的。

我想重载基类中的readConfig函数,其中基类中的每个重载函数最终都将调用纯虚拟形式,例如:

class Base
{
    // ...
    void readConfig(string, string);                                 // read config from file
    virtual void readConfig(boost::property_tree::ptree, string) =0; // read config from ptree
}

void Base::readConfig(string filename, string entry)
{
     boost::property_tree::ptree pt;
     read_xml(filename, pt);
     readConfig(pt, entry);       // <= Calling pure virtual function!
}

基本上,字符串版本只是纯虚拟形式的快速包装。 编译时,出现错误:

no known conversion for argument 1 from std::string to boost::property_tree::ptree`

如此看来,非虚拟功能(来自Base )未被识别为可用。 我检查了派生类的定义是否正确:

class Deriv : public Base
{
    // ...
    void readConfig(boost::property_tree::ptree, string); // implement virtual, error is on this line
}

void Deriv::readConfig( boost::property_tree::ptree pt, string entry)
{
    //...
}

请注意,我省略了很多const -correctnes,通过引用传递等,以使代码更具可读性。

我该怎么做才能解决此问题? 在非虚拟函数中使用纯虚拟成员函数是一个好主意吗?

请参阅标题为“什么是警告,警告:派生:: f(char)隐藏基数:: f(double)?”的FAQ项目。” 可以在常见问题解答的许多镜像中找到,包括常见问题解答的原始英语版本

在发布前检查FAQ通常是个好主意。

您很有可能还会发现标题为“好的,但不是针对当前问题的FAQ”有用,但是有没有一种方法可以模拟这种行为,就像动态绑定对基类的构造函数中的此对象起作用一样? ,此外,如果这变得有意义,那么您可能也有兴趣阅读我有关DBDI问题的博客文章

明显的错别字是显而易见的:

virtual void readConfug

代替

virtual void readConfig

另外,您要实现的方法称为模板方法模式 FYI。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM