Home > Mobile >  How to link to other code implementation?
How to link to other code implementation?

Time:10-13

How to link duplicate implementation with different name? method getWindowTitle and getText have same implementation.

class Window 
{
  public:
    Window();
    void getWindowTitle()
    {
      cout << "Text";
    }
};

class Button
{
  public:
    Button();
    // i want implementation of get title inside getText
    void getText()
};

CodePudding user response:

The question is not very clear but if you would like to avoid copying the code, you may have many solutions. However each solutions may have drawbacks (typically, impacting the Button class when you modify the Window class, which may not be what you want)

For instance:

  • declare the getWindowTitle() as static and simply reuse it within the Buttonclass
#include <iostream>

class Window
{
  public:
    Window();
    static void getWindowTitle()
    {
      std::cout << "Text";
    }
};

class Button
{
  public:
    Button(){}
    // i want implementation of get title inside getText
    void getText()
    {
        Window::getWindowTitle();
    }
};

int main()
{
    Button a;
    a.getText();
}
  • you may inherit Button from the class Window
#include <iostream>

class Window
{
  public:
    Window(){}
    static void getWindowTitle()
    {
      std::cout << "Text";
    }
};

class Button: public Window
{
  public:
    Button(){}
    // i want implementation of get title inside getText
    void getText()
    {
        this->getWindowTitle();
    }
};

int main()
{
    Button a;
    a.getText();
}

CodePudding user response:

usually widgets libraries got a base class 'widget' or 'window' that collects all the widget's common implementation and all other more complex class are derived from it. let's do an example:

class Widget
{
public:
    void SetPosition(int x, int y);
    void SetSize(int w, int h);
    void SetName(const std::string& name);
    
    void GetPosition(int* x, int* y);
    void GetSize(int* w, int* h);
    std::string GetName();
    std::string GetTitle();
};


class Button : public Widget
{
public:
    //Button class inherited all public and protected members of Widget
    std::string GetText(){
        return GetTitle();
    }
}

  •  Tags:  
  • c
  • Related