C++: syntax for accessing member struct from pointer to class

后端 未结 5 1898
醉话见心
醉话见心 2021-01-18 01:16

I\'m trying to access a member structs variables, but I can\'t seem to get the syntax right. The two compile errors pr. access are: error C2274: \'function-style cast\' : i

5条回答
  •  天涯浪人
    2021-01-18 01:42

    Bar is inner structure defined inside Foo. Creation of Foo object does not implicitly create the Bar's members. You need to explicitly create the object of Bar using Foo::Bar syntax.

    Foo foo;
    Foo::Bar fooBar;
    fooBar.otherdata = 5;
    cout << fooBar.otherdata;
    

    Otherwise,

    Create the Bar instance as member in Foo class.

    class Foo{
    public:
        struct Bar{
            int otherdata;
        };
        int somedata;
        Bar myBar;  //Now, Foo has Bar's instance as member
    
    };
    
     Foo foo;
     foo.myBar.otherdata = 5;
    

提交回复
热议问题