#include <bits/stdc++.h>
using namespace std;
class A {
int x;
public:
class B {
public:
int y;
B(int _y) : y(_y) {}
explicit operator A() const {
return A(y);
}
};
explicit A (int _x) : x(_x) {}
explicit A (const A& o) : x(o.x) {}
};
typedef unsigned int size_type;
int main () {
return 0;
}
Error: g++ -Wall -I./ -I/home/abdelrahman/main-repo/ -o "testt" "testt.cpp" (in directory: /home/abdelrahman/Desktop)
testt.cpp: In member function ‘A::B::operator A() const’: testt.cpp:11:14: error: no matching function for call to ‘A::A(A)’ return A(y); ^
Compilation failed.
最佳答案
显式标记复制构造函数意味着不允许编译器隐式使用它,这就是函数返回时发生的情况——当返回值时,隐式使用复制构造函数被复制“出”函数。
当你传递一个参数时也会发生同样的情况——编译器隐式地使用复制构造函数来创建参数。
以下是一个由于这些原因而失败的最小示例:
class A
{
public:
A(){}
explicit A(const A&){}
};
void g(A a)
{
}
A f()
{
A a;
return a; // Fails; no suitable constructor
}
int main()
{
A a;
g(a); // Fails; no suitable constructor
}
您唯一可以制作的拷贝是显式拷贝——源代码显式复制对象的拷贝,例如
A a;
A b(a); // Succeeds because this is an explicit copy.
除了转换构造函数之外,在任何事情上使用 explicit
都没有什么意义。
关于c++ - 显式 c++ 关键字 : what is wrong with this code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462033/