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 implementclone::f
(yet) - declares
example
, thereby makingx
known compiler.- friends
clone::f
example
- friends
- implements
clone::f
at each stage provide compiler needs continue on.
best of luck.
Comments
Post a Comment