使用返回值传递到构造函数不起作用

Using return value to pass into constructor doesn't work

本文关键字:构造函数 不起作用 值传 返回 返回值      更新时间:2023-10-16

我正在使用boost::property_tree::ptreeparse_ini来读取ini文件。使用ptree::iterator我正在获取ini部分,并希望使用它们来创建另一个对象。

我有一个名为First的对象,它First(int& i, string& str)

所以我正在尝试使用我从 ptree 函数获得的返回值来构建这样的新对象,例如(posision是我的ptree::iterator

First* one = new First(
    boost::lexical_cast<int>((posision->second).get<int>("number")),
    (posision->second).get<string>("name")
);

但我得到

no matching function for call to ‘First::First(int, std::basic_string<char>)’

所以我尝试像这样投射:

First* one = new First(
    (int&) boost::lexical_cast<int>((posision->second).get<int>("number")),
    (string&) (posision->second).get<string>("name")
);

但后来我得到了

invalid cast of an rvalue expression of type ‘int’ to type ‘int&’

invalid cast of an rvalue expression of type ‘std::basic_string<char>’ to type ‘std::string&

将不胜感激任何帮助或解释。

谢谢!

问题是您无法在参数类型为 l 值引用的地方传递 r 值。 例如

void foo(int& x)
{
    x = 2;
}
int main(void)
{
    foo(5); // won't compile; can't pass r-value to reference parameter
}

如果这是有效的,我们会将值 2 分配给值 5,这是无稽之谈。如果可能的话,你可以声明第一个构造函数来接受 const 引用(不确定这是否适合你,因为你没有发布代码):

First(const int& i, const string& str);

尽管对于基元,最好只作为值传递而不是常量引用:

First(int i, const string& str)

如果你需要它们成为非常量引用(闻起来像一个糟糕的设计),你可以这样做:

int i = boost::lexical_cast<int>((posision->second).get<int>("number"));
string str((posision->second).get<string>("name"));
First* one = new First(i, str);