以下代码引发编译错误:
#include <stdio.h>
class Option
{
Option() { printf("Option()\n"); };
public:
explicit Option(const Option& other)
{
printf("Option(const)\n");
*this = other;
}
explicit Option(Option& other)
{
printf("Option(non-const)\n");
*this = other;
}
explicit Option(const int&)
{
printf("Option(value)\n");
}
};
void foo(Option someval) {};
int main()
{
int val = 1;
Option x(val);
foo(x);
}
抛出的错误是:
main.cpp:31:10: error: no matching function for call to ‘Option::Option(Option&)’
foo(x);
^
main.cpp:5:5: note: candidate: ‘Option::Option()’
Option() { printf("Option()\n"); };
^~~~~~
main.cpp:5:5: note: candidate expects 0 arguments, 1 provided
main.cpp:25:6: note: initializing argument 1 of ‘void foo(Option)’
void foo(Option someval)
如果我从中删除显式关键字,错误就会消失explicit Option(const Option& other)
有人可以向我解释编译错误的原因是什么吗?explicit Option(const Option& other)
另外,如果和之间有区别explicit Option(Option& other)
?