c++ - 我如何构建我的 C++ 代码,以便我只编写一次常用方法?

标签 c++ winforms class inheritance managed

如果 C++.NET 允许多重继承,我会将常用方法放在一个类中并从中派生。

我有派生自 Panel、Label、TabControl 的类......它们具有完全相同的方法。

如何构造我的 C++ 代码,以便只编写一次常用方法?

这是我要添加到每个派生类的属性的一个简单示例。扩展方法听起来很理想,但在 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; }
    }

最佳答案

我不能完全弄清楚你在这里所说的“通用方法”是什么意思,但一般来说命名空间级别的非成员函数是最好的方法(参见标准库中的几乎所有算法)。

如果它确实需要访问您的类的私有(private)属性,那么它可能不是一个通用方法,应该在它所操作的属性存在的继承级别中实现。

几乎可以肯定的是,将通用方法放入您随后从中继承的类中是对继承的滥用:使用继承来扩展,而不是重用。

关于c++ - 我如何构建我的 C++ 代码,以便我只编写一次常用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5412873/

相关文章:

C++问题将8位填充到一个字符中

c++ - 从偏移位置开始复制内存

c# - 在 C# 中调整大小时保留表单纵横比

c# - 拦截鼠标/键盘事件

php - 如何在 Laravel 中添加类别名

c# - 扩展方法与继承

c++ - 在 CDialog 中应用按钮

C++:声明一个在头文件中返回字符串的函数?

c# - WinForm刷新问题

C++ - 没有合适的默认构造函数可用