例如,我创建一个Button类。 Button应该具有自己的文本(带有颜色,大小,字体,间距等),状态和背景。

因为文本标签甚至在其他小部件(文本标签,文本编辑等)中也很有用,所以我将所有所需的内容都放在了另一个类中(称为Label)。

背景颜色也很有用,因此我创建了另一个类-Color,其中包含所有需要的方法-更改,比较...

现在回到Button类。

class Button {
    private:
        Color _bgColor;
        Label _text;

        /* another private members */

    public:
        /* Content of Button class */
};


但是,如果我想更改按钮的背景色怎么办?在这种情况下,我需要编写另外两个方法=> setColorgetColor。实际上,我必须编写为Color类定义的所有方法。

另一种选择是将私有类定义为公共类,并像button.bgColor.setColor()那样访问它们。但是一次调用button.disable而另一次调用button.color.setColor对我来说似乎很奇怪。

还有其他我不知道的选择吗?谢谢你的帮助。

最佳答案

您是对的,当某些东西具有属性时,这些属性需要以某种方式公开,这可能导致代码膨胀。但是,与所有事物一样,简单的抽象层可以使事物变得更容易。

您可以为这些类型的属性提供“帮助程序类”,并将它们用作混合。这将使代码尽可能保持较小

class HasLabel
{
public:
   void SetLabelText(const std::string& text);
   const std::string& GetLabelText() const;

private:
   Label label_;
};

class HasBackgroundColor
{
public:
   void SetBackgroundColor(const Color& color);
   const Color& GetBackgroundColor() const;

private:
   Color color_;
};

class Button : private HasBackgroundColor, private HasLabel
{
public:
   // Expose BkColor
   using HasBackgroundColor::SetLabelText;
   using HasBackgroundColor::GetLabelText;

   // Expose Label
   using HasLabel::SetLabelText;
   using HasLabel::GetLabelText;
};


您还可以使用公共继承,然后不必使用using指令,但是是否可以接受(如果Button确实是“是” HasLabel)则是个人喜好问题。

您也可以使用CRTP来减少具有类似mixin的对象的样板代码数量。

关于c++ - CPP:作为另一类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18664744/

10-11 22:36
查看更多