c++ How do I get variables from a class and put it into another class, and put it into a constructor? -
i have 2 h , cpp files. wanna know how call variables abe.h file or abe class bob.h or bob class. please help.
abe.h
#include <iostream> using namespace std; #ifndef abe #define abe class abe { private: int num; public: abe(); abe(int); void shownumber(); }; #endif // abe abe.cpp
#include "abe.h" #include <iostream> using namespace std; abe::abe() { num=45; } abe::abe(int n) { num=n; } void abe::shownumber() { cout<<num; } bob.h
#include "abe.h" #include <iostream> using namespace std; #ifndef bob #define bob class bob { private: abe a; public: bob(abe); void shownum(); }; #endif // bob bob.cpp
#include "abe.h" #include "bob.h" #include <iostream> using namespace std; bob::bob(abe a1) { a=a1; //^not sure a=a1 doing if explain in simple terms or in deatil help. } void bob::shownum() { //how display here?? } so how "num" abe class , use in bob class? please help. thank you!
a=a1assigns abe passed bob's constructor bob's a member. idea use more descriptive variable names , there optimizations gained using initializer list. example:
bob::bob(abe a1):a(a1) { } now bob has abe, can... nothing number abe. abe has allow bob number. redefine abe in 1 of 2 ways:
class abe { private: int num; public: abe(); abe(int); void shownumber(); int getnumber() { return num; } }; now bob can
int number = a.getnumber(); or (and second because less preferred option because tightly couples bob , abe.
class abe { friend class bob; private: int num; public: abe(); abe(int); void shownumber(); }; bob has total access internals of abe , can mess poor guy if wants to. not nice. anyway, bob can now
int number = a.num; bob can read num, change num, set hopelessly bad values , jerk abe. thing bob friend. other downside bob needs know how abe works on inside , if abe's code changed, bob have change well.
Comments
Post a Comment