【问题标题】:Using return value to pass into constructor doesn't work使用返回值传递给构造函数不起作用
【发布时间】:2015-01-17 18:43:38
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 如果按值返回结果,则不能将其作为非常量引用参数。
  • 无关:你为什么使用new
  • 0x499602d2:因为我需要在一个向量中管理所有这些新对象,并且该向量的类型是一个抽象类,它首先来自...抽象对象...

标签: c++ casting ptree


【解决方案1】:

问题在于,当参数被键入为左值引用时,您不能传递右值。例如

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);

【讨论】:

  • 首先 - 非常感谢!就是这样!第二,为什么 const 引用是好的。为他们分配 r 值?
  • 就是这样 - 你不能为 const 引用赋值。例如void foo(const int&amp; x) { x = 3; } 不合法。 const 引用意味着,虽然参数是一个引用,但它不能以非常量的方式使用(包括分配给它或在其上调用其他非常量方法)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 2022-08-14
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
相关资源
最近更新 更多