我需要创建一个Bar
对象,其中有一个私有对象Foo f
。
然而,Foo
对象参数的值应该由特定方法int genValue()
传递。
如果我在构造函数作用域Bar(){...}
中初始化f
,编译器会报错,类似于没有构造函数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()
传递,我该如何解决问题?同时,我不想使用纯指针(*),但使用智能指针的解决方案可以!
Foo
接受一个引用就没有意义了。只需将Foo
的构造函数更改为Foo(int x) : x(x) { }
即可。 - Jans