0

我正在使用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&

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

谢谢 !

4

1 回答 1

2

问题是您不能在参数被键入为左值引用的情况下传递右值。例如

void foo(int& x)
{
    x = 2;
}

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

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

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

虽然对于原语,最好只作为值而不是 const 引用传递:

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);
于 2014-11-20T02:36:13.727 回答