【问题标题】:Why I am not able to invoke 'explicit a (string x)'?为什么我不能调用'explicit a (string x)'?
【发布时间】:2013-02-24 07:12:46
【问题描述】:

我无法使用对象 a3 调用 'explicit a (string x)',出现两个编译错误,例如:

[错误] 从 'const char*' 到 'int' 的无效转换 [-fpermissive]

[错误] 初始化 'a::a(int)' 的参数 1 [-fpermissive]

我的预期输出是'int int double string';

有人可以帮我消除这些错误吗?感谢您宝贵的时间。

#include<iostream>
#include<string.h>

using namespace std; 


struct a{

    a(int x=0){cout<<" int ";
    }
    inline a (double x){cout<<" double ";
    }
    explicit a (string x){ cout<<" string ";
    }

};


int main()
{
    a a0(NULL);
    a a1=9;
    a a2=1.1;
    a a3=("Widf"); //Error
}

【问题讨论】:

    标签: c++ casting constructor explicit


    【解决方案1】:

    在语法上,C++ 解释

    a a3 = ("Widf");
    

    作为“计算表达式"Widf",然后构造一个名为a3a 类型的对象,该对象被初始化为等于它。”由于"Widf" 具有const char[4] 类型,C++ 只有在存在可用的隐式转换构造函数时才能将a3 初始化为"Widf"。由于您已显式标记了构造函数 explicit,因此此隐式转换不可用,因此出现错误。

    要解决此问题,请尝试将行重写为

    a a3("Widf");
    

    这不会首先尝试评估"Widf",而是直接将其作为参数传递给构造函数。

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      必须通过结构/类名调用显式构造函数:

      a("Widf")
      

      使用相等作为构造函数不是显式的构造函数调用。 你可以使用这个:

      a a3 = a("Widf")
      

      哪个会:

      1. 创建一个临时对象a
      2. 使用复制构造函数创建 a3

      编译器优化器应该能够对此进行优化。

      或者,你可以写

      a a3("Widf")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-03
        • 2021-10-13
        • 1970-01-01
        • 2010-12-30
        • 1970-01-01
        相关资源
        最近更新 更多