我需要创建一个Bar
对象,它有一个私有对象Foo f
.
然而,价值Foo
对象参数应通过特定方法传递int genValue()
.
如果我初始化f
在构造函数范围内Bar(){...}
,编译器报错,比如没有构造函数Foo()
.
如果我这样构建Bar(): f(genValue())
,编译器会报错:
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()
?而且,我不想使用纯指针(*),但是使用智能指针的解决方案是可以的!
A non-const
参考参数,例如int&
,只能指“左值”,它是named多变的。
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
, not int&
nor const int&
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)