c++ - Declare static functions as friend function? -
i have class myclass
declaration in header file interface.h
, static functions (foo
, bar
, few more) in file1.cpp
. static functions used inside file1.cpp
need modify private/protected members of myclass`.
// in "interface.h" class myclass { // maybe declare friend? // friend static void foo(myclass &ref); private: double someval; } // in "file1.cpp" static void foo(myclass &ref) { ref.someval = 41.0; } static void bar(myclass &ref) { ref.someval = 0.42; } // function uses foo/bar void dosomething(myclass &ref) { foo(ref); }
idea 1: somehow declare them friends of myclass
?
why not good: static , in different compilation unit. besides expose them user of myclass
not need know them.
idea 2: don't have idea 2.
sort of linked: is possible declare friend function static?
sort of linked: possible declare friend function static?
personally find whole friend
thing bit of hack breaks encapsulation you've asked valid question , answer can achieve want helper class:
file1.h
class myclass { private: double someval; friend class myclasshelper; };
file1.cpp
#include "file1.h" struct myclasshelper { static void mutatemyclass(myclass& ref) { ref.someval=42; } }; // in "file1.cpp" static void foo(myclass &ref) { myclasshelper::mutatemyclass(ref); }
are sure want this? sure don't want encapsulate myclass's mutators inside myclass itself?
Comments
Post a Comment