开发者

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

开发者 https://www.devze.com 2023-02-19 22:04 出处:网络
If C++.NET allowed multiple inheritance, I would have my common methods in a class and derive from it.

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.


Put your common methods in a Utility class, create an instance of this class (pass the object to work on to the constructor) when needed.


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.


You could use .NETs "extension methods" if you don't need to access private/protected fields of an object.

0

精彩评论

暂无评论...
验证码 换一张
取 消