" const char *"之间的歧义和" Platform :: String ^" UWP上的cpp构造函数

时间:2017-10-20 15:28:40

标签: string constructor uwp const c++-cx

我遇到了类I中的构造函数的问题,我试图用c ++编写UWP。这是它的最小版本:

class MyClass {
    public:
        inline MyClass() {}

        inline MyClass(const char* s) : version(1) { }

        inline MyClass(Platform::String^ s) : version(2) { }

    private:
        int version;
};

我正在使用Visual Studio 2017中的默认UWP空白项目。 我希望能够写下这个:

MyClass s1 = MyClass("hello");
MyClass s2 = "hello";
MyClass s3 = (MyClass)"hello";

但是编译器会在这3行上抛出3个错误:

error C2440: '<function-style-cast>': cannot convert from 'const char [6]' to 'MyClass'
note: No constructor could take the source type, or constructor overload resolution was ambiguous
error C2440: 'initializing': cannot convert from 'const char [6]' to 'MyClass'
note: No constructor could take the source type, or constructor overload resolution was ambiguous
error C2440: 'type cast': cannot convert from 'const char [6]' to 'MyClass'
note: Conversion requires a constructor or user-defined-conversion operator, which can't be used by const_cast or reinterpret_cast

如果我添加&#34;显式&#34; Platform :: String构造函数的关键字,如下所示:

      explicit inline MyClass(Platform::String^ s) : version(2) { }

然后第二个错误C2440&#39;初始化&#39;消失了,MyClass s2 =&#34;你好&#34;有效,但其他错误仍在那里。

我需要从&#34; Platform :: String ^&#34;构建我的类。和标准&#34; const char *&#34;。

由于未知原因,我认为从硬编码字符串中可以进行某种自动转换,例如&#34; hello&#34;和Platform :: String ^导致编译时出现歧义。

在示例写作中:

MyClass s0 = MyClass((const char *)"hello");

就像一个魅力!没有更多的歧义,因为它真的被转换为&#34; const char *&#34;。但我不想每次都要写这个演员。

有人知道如何解决这个问题吗?

预付Thanx!

0 个答案:

没有答案