简体   繁体   中英

How can I structure my C++ code so that I only write my common methods once?

If C++.NET allowed multiple inheritance, I would have my common methods in a class and derive from it.

I have classes derived from Panel, Label, TabControl ... which have the same methods exactly.

How can I structure my C++ code so that I only write my common methods once?

Here is a simple example of a property I want to add to each derived class. Extension methods sound ideal, but don't exist in C++.

private: int panelBottomMargin;
public:
    [Browsable(true)]
    [CategoryAttribute("Layout"), DescriptionAttribute(
        "Specify the gap between the last control and the bottom of the panel"),
    DefaultValueAttribute(panelBottomMarginDefault)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility::Visible)]
    property int PanelBottomMargin
    {
        int get() { return this->panelBottomMargin; }
        void set(int margin) { this->panelBottomMargin = margin; }
    }

I can't quite make out for sure what you mean by "common methods" here, but generally speaking namespace level non-member functions are the best way to do that (see pretty much every algorithm in the standard library).

If it actually needs access to private attributes of your class then it's probably not a common method and should be implemented in the level of inheritance where the attribute it operates on exist.

It's almost certainly an abuse of inheritance to put common methods into a class that you then inherit from: Use inheritance to extend, NOT to reuse.

将常用方法放在Utility类中,并在需要时创建此类的实例(将对象传递给构造函数)。

What is wrong with static methods? Or instantiating a new class which can operate on objects of the type given? Its best to not abuse inheritance in ways which clearly don't follow the "is-a" doctrine - use "has-a" whenever possible.

Generally, if MI is being considered as a solution to your problem which does not involve "mixin" type semantics, you should consider a new solution.

如果不需要访问对象的私有/受保护字段,则可以使用.NET的“ 扩展方法 ”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM