【发布时间】:2012-05-05 19:09:07
【问题描述】:
我正在尝试创建一个基类来定义所有派生类的接口。
我想要一个函数,允许读取该类的配置文件,使用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,通过引用传递等,以使代码更具可读性。
我能做些什么来解决这个问题?在非虚函数中使用纯虚成员函数是个好主意吗?
【问题讨论】:
-
Deriv.h,我声明函数的那一行。 -
您实际上不会在正确编写的程序中调用纯虚拟函数。相反,您会调用对应的最衍生的覆盖,其中至少有一个。
-
你的程序真的会因为“调用纯虚函数”而崩溃吗?
-
@KerrekSB 不,它只会唠叨转化率
-
编译器错误实际发生在哪里?当然,您不能指望从
Derived中获得Base:readConfig(string, string),除非您明确将其称为Base::readConfig(),或者将using Base::readConfig;添加到Derived。
标签: c++ inheritance pure-virtual