简体   繁体   中英

Defining declared member function inside struct

struct a_t {
  struct not_yet_known_t;
  struct b_t {
    void f(not_yet_known_t* m);
  };
  struct c_t {
    b_t b;
    //...
  };
  struct not_yet_known_t {
    c_t c;
    //...
  };

  // ERROR HERE
  void b_t::f(not_yet_known_t* m) {
    // code comes here
  }
};

int main() {
  a_t::not_yet_known_t m;
  a_t::b_t b;
  b.f(&m);
}

Is it possible to define a_t::b_t::f inside a_t:: scope some way? Or if we could access global scope inside a_t:: but not actually pasting the code outside a_t:: scope?

Error I get:

main.cpp:16:13: error: non-friend class member 'f' cannot have a qualified name
  void b_t::f(not_yet_known_t* m) {
       ~~~~~^

The function

void f(not_yet_known_t* m);

is not a member of the structure struct a_t and not its friend function. So it may not be defined within the structure struct a_t.

You can define it outside the structure declaration as for example

struct a_t {
  struct not_yet_known_t;
  struct b_t {
    void f(not_yet_known_t* m);
  };
  struct c_t {
    b_t b;
    //...
  };
  struct not_yet_known_t {
    c_t c;
    //...
  };
};


  void a_t::b_t::f(a_t::not_yet_known_t* m) {
    // code comes here
  }

You may define within a class either its own member functions or its friend functions that are not members of other classes.

struct a_t {
  struct not_yet_known_t;
  struct b_t {
    void f(not_yet_known_t* m){ _b_t_f(this, m); }
  };
  struct c_t {
    b_t b;
    //...
  };
  struct not_yet_known_t {
    c_t c;
    //...
  };

  static void _b_t_f(b_t* b, not_yet_known_t* m) {
    // code comes here
  }
};

Instead of declaring a_t::b_t::f you can define it to call another function then define that function in outside of a_t::b_t.

You can use this way if you don't want to go outside of struct a_t . I suggest naming that function _b_t_f something like struct name + function name to be sure it will never collide with other things.

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