Error: cannot bind non-const lvalue reference of type ‘intamp;’ to an rvalue of type ‘int’(错误:无法将“int类型的非常量左值引用绑定到“int类型的右值)
问题描述
我需要创建一个 Bar
对象,它有一个私有对象 Foo f
.
I need to create a Bar
object, which has a private object Foo f
.
但是Foo
对象参数的值应该通过特定的方法int genValue()
来传递.
However, the value of Foo
object parameter should be passed by the specific method int genValue()
.
如果我在构造函数作用域 Bar(){...}
中初始化 f
,编译器会大喊错误,就像没有构造函数 Foo()
.
If I initialize f
in the constructor scope Bar(){...}
, the compiler yell error, something like there is no constructor Foo()
.
如果我像这样构造Bar(): f(genValue())
,编译器会报错:
If I construct like this Bar(): f(genValue())
, the compiler yells the error:
test.cpp: In constructor ‘Bar::Bar()’:
test.cpp:16:19: error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
Bar(): f(genValue()){
~~~~~~~~^~
test.cpp:7:2: note: initializing argument 1 of ‘Foo::Foo(int&)’
Foo(int &x) {
^~~
示例代码:
class Foo {
public:
Foo(int &x) {
this->x = x;
}
private:
int x;
};
class Bar {
public:
Bar(): f(genValue()){
}
private:
Foo f;
int genValue(){
int x;
// do something ...
x = 1;
return x;
}
};
int main() {
Bar bar ();
return 0;
}
如果我不想修改 Foo
类并且它的参数值应该从 genValue()
传递,我该如何解决这个问题?而且,我不想使用纯指针 (*),但使用智能指针的解决方案是可以的!
How can I fix the problem, if I don't want to modify Foo
class and its argument value should be passed from genValue()
? And, I don't want to use pure pointer (*), but a solution with smart pointer is okay!
推荐答案
非const
引用参数,例如int&
,只能引用一个左值",这是一个命名变量.
A non-const
reference parameter, such as an int&
, can only refer to an "lvalue," which is a named variable.
auto takes_nonconst_reference = [](int&){};
auto takes_const_reference = [](const int&){};
auto takes_value = [](int){};
auto returns_int = []{return 42;};
int foo = 1;
// OK
takes_nonconst_reference(foo);
takes_const_reference(foo);
takes_const_reference(returns_int());
takes_value(foo);
takes_value(returns_int());
// compilation error, value returned from a function is not a named variable
takes_nonconst_reference(returns_int());
在这种特殊情况下,由于您的类存储了构造函数参数的副本,您应该按值传递它(int
,而不是 int&
或 const int&
).
In this particular case, since your class is storing a copy of the constructor parameter, you should pass it by value (int
, not int&
nor const int&
).
这篇关于错误:无法将“int&"类型的非常量左值引用绑定到“int"类型的右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:错误:无法将“int&"类型的非常量左值引用
基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17