从C ++中的“接口”访问派生类成员?

问题描述 投票:1回答:1

我正在开发一个UI框架,并尝试使我的代码更易于管理和使用接口(我知道它们只是类。)似乎是最好的选择。

我会给你一个我想做的例子:

在Control基类中,它将具有所有控件将具有的一般成员,例如ID,名称和位置。我希望能够实现一个管理按钮文本的界面。界面将存储和绘制文本。现在要做到这一点,我将需要覆盖Draw()函数,但我不知道我如何转发声明。

伪代码

class ITextAble
virtual void DrawText() override Control::Draw()
{
    Control::Draw();
    GetRenderWindow()->draw(m_text);
}

class Button : public ITextAble

virtual void Draw ()
{
    m_renderWindow->draw(m_shape);
}
sf::RenderWindow * GetRenderWindow () const
{
    return m_renderWindow;
}

如果你不能说我已经是C ++编程的新手了,我不知道这是否可以在C ++中实现,但如果是真的我会再次感到惊讶。

c++ inheritance interface
1个回答
1
投票

你最好使用一些现成的lib,如fltk,wxWidgets,QT,MFC,GTKMM等。你会发现创建一个GUI lib是一个超级复杂的任务。

看起来你不懂接口(纯虚拟类)的概念。这样的类不能有任何成员 - 只有纯虚方法。否则 - 这是一个抽象类。

阅读Scott Meyers:有效的C ++

使用经典动态多态性版本可以覆盖您的概念的东西:

警告!这是糟糕的设计!

更好的方法 - 没有sf :: RenderWindow * GetRenderWindow()const函数。

// a pure virtual class - interface
class IControl {
IControl(const IControl&) = delete;
IControl& operator=(const IControl&) = delete;
protected:
  constexpr IControl() noexcept
  {}
protected:
  virtual sf::RenderWindow * GetRenderWindow() const = 0; 
public:
  virtual ~IControl() noexcept
  {}
}

// an abstract class
class ITextAble:public IControl {
  ITextAble(const ITextAble&) = delete;
  ITextAble& operator=(const ITextAble&) = delete;
protected:
   ITextAble(const std::string& caption):
     IControl(),
     caption_(caption)
  {} 
   void DrawText();
public:
   virtual ~ITextAble() noexcept = 0;
private:
   std::string caption_;
};

// in .cpp file

void ITextAble::DrawText()
{
  this->GetRenderWindow()->draw(caption_.data());
}

ITextAble::~ITextAble() noexcept
{}

// 
class Button :public ITextAble
{
public:
  Button(int w, int h, const char* caption) :
    ITextAble(caption),
    window_(new sf::RenderWindow(w,h) ),
  {}
  void show() {
     this->DrawText();
  }
  virtual ~Button() noexecept override
  {}
protected:
  virtual sf::RenderWindow* GetRenderWindow() const override {
    return window_;
  }
private:
  sf::RenderWindow* window_;
};

// pointer on reference
Button *btn = new Button(120, 60, "Click me");
btn->show();
© www.soinside.com 2019 - 2024. All rights reserved.