为什么不能在带有const引用参数的构造函数中使用临时值

Why a temp value cannot be used in a constructor with a const reference argument?

本文关键字:构造函数 参数 不能 引用 const 为什么      更新时间:2023-10-16

代码如下

class A {};
class B
{
public:
    B(const A& a) {}
    void fun() {}
};
int main(int argc, char *argv[])
{
    B b(A());
    b.fun(); // Error: left of '.fun' must have class/struct/union  
    A a;
    B b2(a);
    b2.fun(); //Okay
    return 0;
}

为什么?

代码

 B b(A());

没有声明B的对象,而是函数b的函数声明,该函数返回类型为B的对象,并接受单个(未命名)参数,该参数是返回类型为A的函数(并且不接受输入)。(引用以下链接)。因此,您看到了这个错误。

参见c++ most vexing parse