使用返回值传递到构造函数不起作用
Using return value to pass into constructor doesn't work
我正在使用boost::property_tree::ptree
和parse_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);
相关文章:
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 子类化 STL 容器:范围构造函数不起作用
- 带有此指针的模板类多重继承构造函数不起作用?
- C++:在没有 lvalue 的情况下调用时复制构造函数不起作用
- 为什么我的右值复制构造函数不起作用
- 矩阵模板类复制构造函数不起作用?
- OOP,构造函数不起作用
- 为什么我的链接数据类型复制构造函数不起作用?
- 回退到复制构造函数不起作用
- C++VS2013:覆盖默认构造函数不起作用
- 复制构造函数不起作用,无法修改副本
- 为什么我的结构中映射的构造函数不起作用
- 为什么我的派生类构造函数不起作用
- 复制构造函数不起作用
- 重载 [] 运算符和复制构造函数不起作用
- 为什么我的 strcmp 构造函数不起作用
- 为什么这个移动构造函数不起作用
- 使用返回值传递到构造函数不起作用
- C++ 异常的双重释放损坏错误(复制构造函数不起作用)
- 为什么我的复制构造函数不起作用?