从C++中的"interface"访问派生类成员?
Accessing a derived class members from an "interface" in C++?
我正在开发一个UI框架,并试图使我的代码更易于管理,并使用接口(我知道它们只是类(似乎是最好的选择。
我给你举个例子来说明我想做什么:
在控件基类中,它将具有所有控件将具有的常规成员,例如 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 库是一项超级复杂的任务。
看起来您不了解界面(纯虚拟类(概念。这样的类不能有任何成员 - 只有纯虚拟方法。否则 - 这是一个抽象类。
阅读斯科特·迈耶斯:有效的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();
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 在 C++ 中用派生类型重写成员函数
- 如果基类包含双指针成员,则派生类的构造函数
- 在派生类中绑定非静态模板化成员函数
- 为什么派生类的好友不能使用受保护的成员?
- 在派生类中使用基类的私有成员变量的最佳方法
- 派生类如何获取基的成员?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 调用派生类成员函数
- 从模板化父类中的派生内部类访问受保护的成员变量
- 将基类的成员函数重载到其他派生类C++
- 派生的成员 通过指向基、static_cast、crtp、删除模板的指针
- C++ 使用派生类方法更改基类数据成员
- 派生类看不到基类成员
- 使用派生类中的静态成员而不是基类
- 是否可以使用 using 将基类中的公共成员重新声明为派生类中的私有成员?
- 如何将派生类中的成员函数作为回调传递?