开发者

non-static data member initializers questions

I've built MinGW from trunk-version GCC-4.7.0: http://code.google.com/p/mingw-builds/downloads/list

In the description of changes of this version it is said that non-static data member initializers are implemented: http://gcc.gnu.org/gcc-4.7/changes.html

http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2756.htm

When I try to compile such an example:

#include <iostream>
#include <string>

struct type {
   type()
      :i(33)
   {}

   int i;
   std::string s("string");
};

int main() {
   type t;
   std::cout << t.i << " : " << t.s << std::endl;
}

I get a ton of errors, and this one is in the end:

main.cpp:16:35: note: 'std::string (type::)(int) {aka std::basic_string (type::)(int)}' is not derived from 'const std::basic_string<_CharT, _Traits, _Alloc>' main.cpp:16:35: note: could not 开发者_如何转开发resolve address from overloaded function 't.type::s'

But according to the documentation, the code is correct.


The problem seems to be an ambiguity in determining whether you are declaring a function or an object, and the compiler is choosing the function.

You should try initializing the string using this syntax instead:

std::string s = "string";

If we follow the link from the GCC Release Notes concerning non-static data member initializers (proposal N2756), they mention this in problem 1, with this resolution note:

CWG had a 6-to-3 straw poll in Kona in favor of class-scope lookup; and that is what this paper proposes, with initializers for non-static data members limited to the “= initializer-clause” and “{ initializer-list }” forms.


The data member must be initialized by brace-or-equal-initializers. Visit http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2756.htm

8.5 Initializers [dcl.init]

Change the grammar for initializer:

initializer:

= (  expression-list  )

brace-or-equal-initializer:

=  initializer-clause

   braced-init-list
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜