【问题标题】:Why can the simplest C++ code not be compiled?为什么最简单的C++代码编译不出来?
【发布时间】:2013-10-15 01:57:19
【问题描述】:
template<class CharType>
struct MyString
{
    MyString()
    {}

    MyString(CharType*)
    {}
};

int main()
{
    char* narrow_str = 0;
    MyString<char>(narrow_str); // error C2040
}

我的编译器是 VC++ 2013 RC。

最简单的代码无法编译,因为错误C2040。

错误 C2040:“narrow_str”:“MyString”的级别不同 间接来自 'char *'

为什么?

【问题讨论】:

  • 你认为的构造函数调用其实不是

标签: c++ templates compiler-errors temporary-objects type-deduction


【解决方案1】:

问题是这实际上没有被解析为构造函数调用,而是作为变量定义。问题是你已经定义了一个变量narrow_str。您可能已经知道这一点,但您可以通过为其命名来轻松解决此问题。

template<class CharType>
struct MyString
{
    MyString()
    {}

    MyString(CharType*)
    {}
};

int main()
{
    char* narrow_str = 0;
    MyString<char> ns(narrow_str); // error C2040
}

顺便说一句,这也是在函数参数中使用这种类型的语法时最令人头疼的解析的来源。

说实话,虽然我很惊讶你得到一个不同的错误,因为 g++ 和 clang 都给了我一个明确的错误。

【讨论】:

    【解决方案2】:

    您在创建结构时的语法是错误的。
    改变

        MyString<char>(narrow_str); // error C2040
    

        MyString<char> myString(narrow_str); 
    

    会好的。

    【讨论】:

    • 我认为他知道他可以这样做,但想知道为什么第一个不编译,他认为他正在创建一个临时的
    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 2010-10-24
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多