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

核能气质少年 提交于 2019-12-01 16:05:53

You only define a struct there, not allocate one. Try this:

class Foo{
public:
    struct Bar{
        int otherdata;
    } mybar;
    int somedata;
};

int main(){
    Foo foo;
    foo.mybar.otherdata = 5;

    cout << foo.mybar.otherdata;

    return 0;
}

If you want to reuse the struct in other classes, you can also define the struct outside:

struct Bar {
  int otherdata;
};

class Foo {
public:
    Bar mybar;
    int somedata;
}

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;

You create a nested structure, but you never create any instances of it within the class. You need to say something like:

class Foo{
public:
    struct Bar{
        int otherdata;
    };
    Bar bar;
    int somedata;
};

You can then say:

foo.bar.otherdata = 5;

You are only declaring Foo::Bar but you don't instantiate it (not sure if that's the correct terminology)

See here for usage:

#include <iostream>

using namespace std;

class Foo
{
    public:
    struct Bar
    {
        int otherdata;
    };
    Bar bar;
    int somedata;
};

int main(){
    Foo::Bar bar;
    bar.otherdata = 6;
    cout << bar.otherdata << endl;

    Foo foo;
    //foo.Bar.otherdata = 5;
    foo.bar.otherdata = 5;

    //cout << foo.Bar.otherdata;
    cout << foo.bar.otherdata << endl;

    return 0;
}
struct Bar{
        int otherdata;
    };

Here you have just defined a structure but not created any object of it. Hence when you say foo.Bar.otherdata = 5; it is compiler error. Create a object of struct Bar like Bar m_bar; and then use Foo.m_bar.otherdata = 5;

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!