简体   繁体   中英

Calling functions from other classes

I want to use a function from my Page class but I do not want to inherit from it. Is there another way I can use the onPage(vector<string> vec) function in my element and elementX class without using inheritance? Would association Work? I was thinking that.

Code is below:

class Page
{
    string str;
    vector<string>::iterator it;

    void onPage(vector<string>vec);
};

class element
{
    Page p;
};

class elementX : public element
{
};

Declare it public , so foreign classes can access it.

class Page
{

   string str;
   vector<string>::iterator it;

 public:
   void onPage(vector<string>vec);


};

(you can use public , private and protected to control access to class members, make sure to read them all up. private is the default for classes).

Yes you can. The issue I can see is that you did not declare the void onPage(vector<string>vec); function as public (place public: before the function), since class members are private (hidden for other classes) in C++ by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM