2016-04-29 25 views
1

这是代码:Visual Studio 2015字符串文字不总是不变?

#include <iostream> 
using namespace std; 

struct ConstStr 
{ 
    char const* const Str; 
    constexpr struct ConstStr(char const* str) :Str(str) {} 
}; 

struct Container { 
    static constexpr struct ConstStr hey{ "hey" }; 
}; 


struct StructScope1 
{ 
    struct ConstStr { 
     char const* const Str; 
     constexpr ConstStr(char const* str) :Str(str) {} 
    }; 
    struct Container { 
     static constexpr StructScope1::ConstStr hey{ "hey" }; 
    }; 
}; 

struct StructScope2 
{ 
    struct Container { 
     static constexpr ConstStr hey{ "hey" }; 
    }; 
}; 

struct Container2 { 
    static constexpr struct StructScope1::ConstStr hey { "hey" }; 
}; 

int main() 
{ 
    cout << "Hello World" << endl; 
    cout << "Container::hey.Str " << Container::hey.Str << endl; 
    cout << "StructScope1::Container::hey.Str " << StructScope1::Container::hey.Str << endl; 
    cout << "StructScope2::Container::hey.Str " << StructScope2::Container::hey.Str << endl; 
    cout << "Container2::hey.Str " << Container2::hey.Str << endl; 
} 

我使用Visual Studio 2015对于一些原因,StructScope1::Container::hey声明/初始化失败编译。它给出了错误

表达必须有一个恒定的值

但我在其他地方初始化相同的代码,它工作得很好。这是一个编译器错误,还是我错过了什么?

+0

“_in其他places_” 像什么或在哪里? –

回答

1

我认为这是误导性的编译错误信息。

这工作:

struct StructScope1 
{ 
    struct ConstStr { 
     char const* const Str; 
     constexpr ConstStr(char const* str) :Str(str) {} 
    }; 
    struct Container; 
}; 

struct StructScope1::Container{ 
    static constexpr StructScope1::ConstStr hey{ "hey" }; 
}; 

除非我外面定义嵌套类,在构造函数之前定义的hey尝试(构造函数必须看到标准的规则已建成hey)。

锵是位更加清晰:

a.cpp:23:49: error: constexpr variable 'hey' must be initialized by a constant expression 
    static constexpr StructScope1::ConstStr hey{ "hey" }; 
              ^~~~~~~~~~~~ 
a.cpp:23:49: note: undefined constructor 'ConstStr' cannot be used in a constant expression 
a.cpp:20:19: note: declared here constexpr ConstStr(char const* str) :Str(str) {} 
+0

我想我明白你在说什么。当在StructScope1中定义StructScope1 :: Container,并且在StructScope1中定义StructScope1 :: ConstStr时,则在StructScope1 :: ConstStr :: ConstStr(构造函数)之前定义StructScope1 :: Container :: hey。所以嘿试图在定义它之前使用这个析构函数。那是对的吗? – user1646801

+0

我的意思是构造函数,而不是析构函数。显然,我无法编辑我的评论来解决这个问题。 – user1646801

+0

@user您可以删除并写入新评论。 ;;是的,那将是我的观察。我会留下解释为什么发生在一些规格专家。我的解释是静态成员是在构造函数之前定义的,因为构造函数可能需要使用它们(不过,在定义时只能看到声明);虽然它在我的VS2015上崩溃,所以可能不安全(工作正常w/clang) – krOoze