CPP:Class作为另一个类中的私有成员

时间:2013-09-06 19:00:45

标签: c++ class methods

例如,我创建了一个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一次打电话似乎很奇怪。

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

3 个答案:

答案 0 :(得分:1)

  

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

你为什么这样做? 只需定义一个用于设置颜色的函数SetBackgroundColor(Color &newColor)和用于访问它的const Color& GetBackgroundColor() const

答案 1 :(得分:1)

你是正确的,当某些东西具有属性时,这些属性需要以某种方式暴露,这可能导致代码膨胀。然而,就像所有事情一样,简单的抽象层可以使事情变得更容易。

您可以为这些类型的属性提供“帮助程序类”,并将它们用作mixins。这将使代码尽可能小,同时仍然

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的对象的样板代码量。

答案 2 :(得分:0)

  

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

不正确。您只需要编写这两种方法。其他任何事情都只通过getColor返回值发生。例如,要测试两个按钮是否具有相同的颜色,请编写:

if (button1.getColor() == button2.getColor())

if (button1.hasSameColor(button2))

也就是说,除非您想隐藏Button使用Color类作为“实现细节”。我不建议这样做。处理颜色的程序通常应将颜色视为值类型,类似于普通数字,点,矢量等。

相关问题