c++ - 从 C++ 中的 "interface"访问派生类成员?

标签 c++ inheritance interface

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

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

在 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++ 中是否可以做到这一点,但如果是真的,我会再次感到惊讶。

最佳答案

你最好使用一些现成的库,如 fltk、wxWidgets、QT、MFC、GTKMM 等。 您会发现创建 GUI 库是一项 super 复杂的任务。

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

阅读 Scott Meyers:Effective 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();

关于c++ - 从 C++ 中的 "interface"访问派生类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49056373/

相关文章:

c++ - 如何使用 C 或 C++ 编程改变 USB 上的电压并检测 USB 上的变化电压

c++ - 迭代但不取消引用 C++ 中的无效迭代器

c++ - 在二维矩阵上使用 std::max_element

css - 在 CSS 中使用对象引用

.net - 为什么我创建的新 WPF Windows 不是从 Window 继承的?

java - 为什么扩展接口(interface)不会使它的方法返回更精确的类型?

C++控制台屏幕大小

Scala:用 val 覆盖 def

java - 我无法使用删除(int)方法,符号未找到错误

java - 如何影响 Void 方法的返回值