class - c++ how to create classes that are interdependent -
i have storage class. members of class modified. each time member modified, i'd save state of class (clone class instance , save it). i'd create new class, save these states.
for example:
say have storage class in file storage.h
class storage { public: int m_cnt; <lots of other members...> storagehistory m_his; }; and storagehistory class in file storagehistory.h
class storagehistory { public: std::vector<storage> m_history_vec; }; assumptions:
storagehistoryclass should kept in storage class. reasonstorageclass main class can accessed in classes/packages. minimize changes in code, i'd storagehistorycoupledstorageclass.storagehistorycannot static or singleton since multiple instance ofstoragecreated.
problems:
- cannot compile code. storage.h needs compiled before storagehistory.h , vice versa
- if
storagehistorycannot stored instorageclass keep it? owner of class?
need define connection between these 2 classed?
first of all: don't make data members public, unless define pure data structure. then: int no c++ type.
now questions: can use forward declarations. since storagehistory used directly in storage, cannot forward declared, storage used in template data member (namely std::vector) in storagehistory, , template not need definition of storage if it's declared variable. need definition when use methods of vector.
so here's untangled code:
storagehistory.h
#include <vector> class storage; class storagehistory { std::vector<storage> m_history_vec; public: /* method declarations */ }; storage.h
#include "storagehistory.h" class storage { int m_cnt; /* <lots of other members...> */ storagehistory m_his; public: /* method declarations */ }; storage.cpp
#include "storage.h" #include "storagehistory.h" //not needed, because implicitly included, thats matter of coding style /* ... storage methods definitions ... */ void storage::changevar(/*...*/) { m_his.push_back(*this); /* ... */ } storagehistory.cpp
#include "storagehistory.h" #include "storage.h" /* ... storagehistory method definitions ... */
Comments
Post a Comment