我正在嘗試使基類定義所有派生類的接口。C++:在非虛函數中使用純虛函數
我想要一個函數,允許讀取該類的配置文件,這是使用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',我聲明函數的那一行。 – romeovs
你實際上不會在正確編寫的程序中調用純粹的病毒函數。相反,你會調用相應的派生率最高的覆蓋,其中至少有一個覆蓋。 –
你的程序是否真的崩潰,說「純虛函數調用」? –