【发布时间】:2021-07-19 16:26:16
【问题描述】:
我需要创建一个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) { }
标签: c++ class constructor