gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:04:10 24 4
gpt4 key购买 nike

我正在开发一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com