c++ - 错误 : cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’

标签 c++ class constructor

我需要创建一个 Bar对象,它有一个私有(private)对象 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() 传递?而且,我不想使用纯指针(*),但是使用智能指针的解决方案是可以的!

最佳答案

一个非const引用参数,例如 int& , 只能引用一个“左值”,它是一个命名变量。

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& )。

关于c++ - 错误 : cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54032945/

相关文章:

c++ - 从模板类调用函数时形成无限循环,请任何人解释

c++ - Argument Dependent Lookup 的逆向解决方法?

c++ - SDL2 C++ 捕获渲染器动画/ Sprite 的视频

objective-c - 告诉自定义委托(delegate)何时调用方法

Java 不确定类型的参数数量不确定

java - 为什么我不能在 Java 中为单个类定义这两个构造函数?

c++ - 获取指向结构的第一个元素的指针

javascript - 设置间隔函数不作为方法

c++ - 为什么我的析构函数被调用,我该如何修复它

c++ - 我可以根据私有(private)/ protected 成员分配类枚举吗?