简体   繁体   中英

const char pointer declaration in struct

I'm trying to do this, but my compiler won't let me:

    struct {
        const char* string = "some text";
    } myAnonymousStruct;

I believe it's because no assignments can be made in a struct declaration - they're supposed to be made in functions or otherwise. But am I really not even allowed to assign const char* variables?
If anyone can let me know what I'm missing, I'd really appreciate it. thx

Members of a struct cannot be default initialized, they must be initialized after an instance struct is created. Since, in your example, myAnonymousStruct is an instance of an unnamed struct, it makes sense to do the following:

struct {
    const char* string;
} myAnonymousStruct = { "some text" };

Most people that look for this behaviour are trying to default initialize values for many instances of a struct. If that is ultimately your desired usage, you may want to consider giving your struct a constructor and initializing members in it instead.

In the following example, foo and bar are distinct structs, both with a member initialized to "some text" .

struct MyStruct {
    const char* str;
    MyStruct() { str = "some text"; }
};

MyStruct foo;
MyStruct bar;

Although, in this case, I typically end up using a class instead.

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