【发布时间】:2020-05-30 06:11:16
【问题描述】:
作为主体,下面的代码是对的。
#include<iostream>
class ABC
{ public:
ABC()
{
std::cout<< "default construction" << std::endl;
}
ABC(ABC& a)
{
std::cout << "copy construction" << std::endl;
}
};
int main()
{
ABC c1 = ABC();
}
无法编译成功:
<source>: In function 'int main()':
<source>:25:13: error: cannot bind non-const lvalue reference of type 'ABC&' to an rvalue of type 'ABC'
25 | ABC c1 = ABC();
| ^~~~~
<source>:10:14: note: initializing argument 1 of 'ABC::ABC(ABC&)'
10 | ABC(ABC& a)
| ~~~~~^
但是,如果将ABC(ABC& a) 替换为ABC(const ABC&),它可以编译。我知道它与关键字const 有一些关系。但我不知道为什么。
您可以在https://godbolt.org/z/jNL5Bd 上查看。我是 C++ 的新手。如果能在这个问题上得到一些帮助,我将不胜感激。
【问题讨论】:
-
将
clang与现代设置一起使用时不会发生这种情况。你用的是什么编译器? -
@tadman 你可以在godbolt.org/z/jNL5Bd 上查看。使用选项“-std=c++11”
-
当然,但我住在 2020 年,所以我使用现代标准。你坚持使用 C++11 有什么原因吗?如果是这样,请感受一下。
-
@tadman 有很多编译器不支持 C++20,尤其是嵌入式系统。
-
您这里的代码与您在编译器资源管理器中提供的代码不同。这里的代码没有给出那个错误。不同之处在于为复制构造函数参数指定
const。
标签: c++ c++11 constructor copy-constructor move-semantics