gpt4 book ai didi

c++ - 构造函数中的奇怪 "candidate expects 1 argument, 0 provided"

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:19 27 4
gpt4 key购买 nike

我正在用 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;
}

关于c++ - 构造函数中的奇怪 "candidate expects 1 argument, 0 provided",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8875957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com