【问题标题】:explicit c++ keyword: what is wrong with this code?显式 c++ 关键字:这段代码有什么问题?
【发布时间】:2017-06-09 15:52:33
【问题描述】:
#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;
}

错误:g++ -Wall -I./ -I/home/abdelrahman/main-repo/ -o "testt" “testt.cpp”(在目录:/home/abdelrahman/Desktop)

testt.cpp:在 成员函数'A::B::operator A() const':testt.cpp:11:14:错误:否 调用‘A::A(A)’的匹配函数 返回 A(y); ^

编译失败。

【问题讨论】:

  • 将构造函数移到class B之前?
  • 例如看这个问题,显式复制构造函数往往不允许按值返回:stackoverflow.com/questions/4153527/…
  • 仅供参考:如果您从 As 复制构造函数中删除显式,它将编译。现在看看为什么。
  • 更多想法:制作复制构造函数explicit有什么意义吗? explicit 的通常原因是避免意外转换,将A 转换(复制)到另一个A 对我来说似乎是安全的。如果需要,现在可以使用=delete 禁用复制构造。
  • 不包含

标签: c++ compiler-errors explicit


【解决方案1】:

将复制构造函数标记为显式意味着不允许编译器隐式使用它,这就是函数返回时发生的情况——在返回值时隐式使用复制构造函数被“复制”出函数。

当你传递一个参数时也会发生同样的情况——编译器隐式使用复制构造函数来创建参数。

以下是由于这些原因而失败的最小示例:

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 没什么意义。

【讨论】:

  • 隐式副本是什么意思?!返回值在哪里进行隐式转换?它不应该只使用A 类型的显式参数调用复制构造函数吗?另外我认为您的代码中还有其他问题,定义另一个构造函数会删除默认构造函数,因此您不应该在返回行中使用它A(),或者您可以自己定义它。
猜你喜欢
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多