简体   繁体   中英

Declare and initialize struct separately?

Can I declare and initialize struct separately?

Ref refType(string strRef) {
    Ref ref;
    if (regex_match(strRef.begin(), strRef.end(), rxIdentifier)) {
        ref = { Var, strRef };
    } else if (regex_match(strRef.begin(), strRef.end(), rxConstant)) {
        ref = { Const, strRef };
    }
    return ref;
}

Doesn't appear to work. Visual Studio complains about the { for initializing the struct.

You can do this in in C++11, but it is not initialization - it is assignment.

http://coliru.stacked-crooked.com/a/819b79c4ee428537

#include <iostream>
using namespace std;
struct S
{
   int a;
};
int main()
{
   S b;
   b={1};
   cout << b.a;
   b={2};
   cout << b.a;
   return 0;
}

Note, VS2010, and VS2012 do not support initializer lists


EDIT: By the way, you may convert your code to:

Ref refType(string strRef) {
    if (regex_match(strRef.begin(), strRef.end(), rxIdentifier)) {
        Ref ref = { Var, strRef };
        return ref;
    } else if (regex_match(strRef.begin(), strRef.end(), rxConstant)) {
        Ref ref = { Const, strRef };
        return ref;
    }
}

Another approach is to use Boost.Optional, but you need constructor in that case:

Ref refType(string strRef)
{
    boost::optional<Ref> ref;
    if(strRef=="1")
    {
        ref=Ref(Var,strRef);
    }
    else
    {
        ref=Ref(Const,strRef);
    }
    return ref.get();
};

Yes, but only in C99 and C++11. Older versions of C and C++ do not support anything like this.

In C99, they're called compound literals , and they look like this:

typedef struct Point
{
    int x, y;
} Point;
...
Point p;
p = (Point){3, 4};

In C++11, they're called extended initializer lists , and they look like this:

struct Point
{
    int x, y;
};
...
Point p;
p = {3, 4};

However, as Evgeny Panasyuk pointed out, Visual Studio is not yet fully compliant with the C++11 standard. Visual Studio 2010 was released before the C++11 standard was finalized, and even then it wasn't fully compliant with the draft standard at the time. Apparently VS2012 hasn't quite caught up yet, either.

As a result, Visual Studio does not yet support extended initializer lists. Visual Studio also does not support C99, and Microsoft has indicated that they do not intend to support C99 any time soon.

No you can't, in C++ Ref ref; is the initialization, subsequent assignments are... well, assignments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM