![](/img/trans.png)
[英]Constructor expecting missing call to other constructor / candidate expects 1 argument, 0 provided?
[英]Weird “candidate expects 1 argument, 0 provided” in constructor
我在C ++中創建一個簡單的線程服務器應用程序,事實是,我使用libconfig ++來解析我的配置文件。 好吧,libconfig不支持多線程,因此我使用兩個包裝類來完成“支持”。 點是,其中一個失敗:
class app_config {
friend class app_config_lock;
public:
app_config(char *file) :
cfg(new libconfig::Config()),
mutex(new boost::mutex())
{
cfg->readFile(file);
}
private:
boost::shared_ptr<libconfig::Config> cfg;
boost::shared_ptr<boost::mutex> mutex;
};
從我的main.cpp文件調用時失敗可怕:
app_main::app_main(int c, char **v) : argc(c), argv(v) {
// here need code to parse arguments and pass configuration file!.
try {
config = app_config("mscs.cfg");
} catch (libconfig::ParseException &e) {
cout << "Parse error at line " << e.getLine() << ": " << e.getError() << endl;
throw;
} catch (libconfig::FileIOException &e) {
cout << "Configuration file not found." << endl;
throw;
}
}
它說:
main.cpp: In constructor ‘app_main::app_main(int, char**)’:
main.cpp:38:54: error: no matching function for call to ‘app_config::app_config()’
main.cpp:38:54: note: candidates are:
../include/app_config.h:15:5: note: app_config::app_config(char*)
../include/app_config.h:15:5: note: candidate expects 1 argument, 0 provided
../include/app_config.h:12:7: note: app_config::app_config(const app_config&)
../include/app_config.h:12:7: note: candidate expects 1 argument, 0 provided
main.cpp:41:39: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] (THIS CAN BE IGNORED, I WAS USING STD::STRING, YET CHANGED IT FOR TESTING PURPOSES)
這很奇怪,因為我明顯地傳遞了一個論點,而且它是一個char *
!
好吧,一如既往,任何幫助將不勝感激。
朱利安。
您正在嘗試默認構建您的配置,然后再分配給它。 但是你沒有默認的構造函數。
將參數傳遞給成員變量的構造函數的正確方法是:
app_main::app_main(int c, char **v) : argc(c), argv(v), config("mscs.cfg")
您仍然可以使用所謂的函數try-block來捕獲異常。 見http://www.gotw.ca/gotw/066.htm
最終代碼:
app_main::app_main(int c, char **v)
try : argc(c), argv(v), config("mscs.cfg")
{
// more constructor logic here
} catch (libconfig::ParseException &e) {
cout << "Parse error at line " << e.getLine() << ": " << e.getError() << endl;
throw;
} catch (libconfig::FileIOException &e) {
cout << "Configuration file not found." << endl;
throw;
}
首先,不要動態分配互斥鎖,它沒有用處。 其次,這是因為你有一個不能默認構造的數據成員,並且你沒有在ctor init列表中初始化它。 另外,永遠不要將字符串文字分配給char*
變量(如果你真的想要使用char指針,它應該是app_config(const char*)
)。
你的app_main::app_main
應該是這樣的:
app_main::app_main(int c, char **v) try
: argc(c), argv(v), config("mscs.cfg") {
} catch (libconfig::ParseException &e) {
cout << "Parse error at line " << e.getLine() << ": " << e.getError() << endl;
throw;
} catch (libconfig::FileIOException &e) {
cout << "Configuration file not found." << endl;
throw;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.