为什么不能在带有const引用参数的构造函数中使用临时值
Why a temp value cannot be used in a constructor with a const reference argument?
代码如下
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
相关文章:
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在按值调用 (c++) 中转发构造函数参数
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 如何在构造函数参数中初始化"std::set"?
- 何时应在构造函数参数中使用 const C++?
- 使用模板化结构作为构造函数参数
- 使用 lambda 作为构造函数参数是否需要C++ 17?
- 如何使输入文本文件成为构造函数参数?c++
- shared_ptr构造函数参数是否应按值传递
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 复制构造函数参数为0
- 用作成员构造函数参数的函数的求值顺序
- 结构中的默认成员值或默认构造函数参数
- C++将引用成员绑定到构造函数参数
- 如何通过可变参数模板将多个构造函数参数转发到数组初始值设定项列表?
- 模板函数指针参数与构造函数参数
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 如何基于构造函数参数模板化类成员函数的代码
- 将派生类构造函数参数传递给受保护的成员
- 如何根据构造函数参数使用超类类型初始化成员变量?