c++ - 显式 c++ 关键字 : what is wrong with this code?

标签 c++ compiler-errors explicit

#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/

相关文章:

c++ - std::map 的插入提示是否有任何位置限制?

c++ - GCC:错误:表达式后出现垃圾 `:0x+57f120'

c++ - 空字符常量

C++显式复制构造函数?

c++ - 多参数构造函数上的显式关键字?

c# - 扫描文档中背景/前景层的分离

c++ - std::chrono::from_stream gcc 可用性,在 gcc 10.1.0 中不可用

makefile - 为什么 gnu make 忽略我的显式模式规则并改用内置的隐式规则?

c++ - C++11 中线程安全局部静态变量初始化的成本?

c++ - Hello World C++