c++ - Member is inaccessible -


class example{ public:     friend void clone::f(example);     example(){         x = 10;     } private:     int x; };  class clone{ public:     void f(example ex){         std::cout << ex.x;     } }; 

when write f normal function, program compiles successful. however, when write f class member, error occurs.

screenshot:

the error you're seeing not root-cause compilation error. artifact of different problem. you're friending member function of class compiler has no earthly clue exists yet,much less exists specific member.

a friend declaration of non-member function has advantage acts prototype declaration. such not case member function. compiler must know (a) class exists, , (b) member exists.

compiling original code (i use clang++ v3.6), following errors actually reported:

main.cpp:6:17: use of undeclared identifier 'clone' main.cpp:17:25: 'x' private member of 'example' 

the former direct cause of latter. doing this instead:

#include <iostream> #include <string>  class example;  class clone { public:     void f(example); };  class example { public:     friend void clone::f(example);     example()     {         x = 10;     }  private:     int x; };  void clone::f(example ex) {     std::cout << ex.x; };  int main() {     clone c;     example e;     c.f(e);    } 

output

10 

this following:

  • forward declares example
  • declares clone, not implement clone::f (yet)
  • declares example, thereby making x known compiler.
    • friends clone::f example
  • implements clone::f

at each stage provide compiler needs continue on.

best of luck.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -