错误:无法将“int&"类型的非常量左值引用绑定到“int"类型的右值

2021-12-09 00:00:00 class constructor c++

我需要创建一个 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&).

相关文章