开发者

from member of nested list, how can I call outside data

struct object {
      string sent ;
      ...// other data declaration
      struct nested {
            void read ( void ) ;
      };
};

In read function, how Can I fill sent ?In other words, how can I call sent

EDIT :

I know this is a trivia开发者_JAVA技巧l question, but I donot know so much about nested structure, and can you give any web-site recommandation


The nested class simply needs a pointer or reference to the enclosing class. This can be passed in via the nested class's constructor.

struct nested 
{
  nested(object& obj) : m_obj(obj) { }

  object& m_obj;
};

You can then access object::sent through the m_obj reference variable.


You need to make some changes to your structure:

struct object {
      std::string sent ;

      struct nested {
            void read ( object& obj ) { obj.sent = "FOO"; }
      } bar;
};

Firstly, given the read function is non static, you need an instance of nested in object (or outside, I was lazy I put it inside), then you need to pass in an instance of object to that function.. you can then call

object foo;
foo.bar.read(foo); // this will set it

EDIT: If you have more than one function in nested that accesses object, in the ctor of object, construct bar with itself (*this), so that like Charles says in his answer, nested has a reference to the "parent instance".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜