问题描述
我需要创建一个 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
code>,编译器大喊错误,类似没有构造函数 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!
推荐答案
A非 const
引用参数,例如 int&
,只能引用左值,即 named 变量。
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'的右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!