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

时间:2012-05-05 19:09:07

标签: c++ inheritance pure-virtual

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

我想要一个允许人们读取该类的配置文件的功能,使用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,通过引用传递等,以使代码更具可读性。

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

2 个答案:

答案 0 :(得分:3)

请参阅标题为“What是什么意思的FAQ项目,警告:Derived :: f(char)隐藏Base :: f(double)?”可在FAQ的众多镜像中找到,包括原始English version of the FAQ

在发布之前查看常见问题解答通常是个好主意。

很有可能你也会发现有用的(虽然不是直接问题)标题为“好的,但是有没有办法模拟这种行为,好像动态绑定在我的基类中对这个对象有效”构造函数?“,如果相关,那么你可能也有兴趣阅读my blog article about the DBDI problem

答案 1 :(得分:2)

显而易见的错字显而易见:

virtual void readConfug

而不是

virtual void readConfig

此外,您正在实施的内容称为模板方法模式,仅供参考。

相关问题