技巧篇:如何重写基类的事件

先说说需求,也就是我们要达到的效果,希望扩展按钮控件,增加一些属性,但同时我们希望默认事件仍使用Click事件,不过,在事件参数中,我们希望能够传递更多的信息,而不是Button.Click默认的参数。

 

当然,我们首先要写一个自定义的事件参数,为了简单起见,我们的自定义按钮控件,增加一个TagNumber属性,它传递一个整型数据,当我们处理控件的Click事件,能够从事件参数类实例中取得我们在这个属性中设置的值,因此,我们需要一个MyButtonClickAgre,它从EventArgs类派生。

    /// <summary>
    /// 自定义事件参数类。
    /// </summary>
    internal class MyButtonClickAgre : EventArgs
    {
        int _value;

        public MyButtonClickAgre(int n)
        {
            this._value = n;
        }

        public int TheNumber
        {
            get { return this._value; }
        }
    }


现在,从Button类派生一个新类。


                
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是代码实现: ```c++ #include<iostream> using namespace std; // 定义抽象类Shape class Shape { public: virtual double calArea() = 0; // 纯虚函数 }; // 定义三角形类Triangle class Triangle : public Shape { public: double base, height; Triangle(double b, double h) { base = b; height = h; } double calArea() { return 0.5 * base * height; } }; // 定义矩形类Rectangle class Rectangle : public Shape { public: double length, width; Rectangle(double l, double w) { length = l; width = w; } double calArea() { return length * width; } }; // 定义正方形类Square class Square : public Shape { public: double side; Square(double s) { side = s; } double calArea() { return side * side; } }; // 定义圆形类Circle class Circle : public Shape { public: double radius; Circle(double r) { radius = r; } double calArea() { return 3.14 * radius * radius; } }; // 定义函数fun,输出图形面积 void fun(Shape* s) { cout << "通过基类指针调用,面积为:" << s->calArea() << endl; } void fun(Shape& s) { cout << "通过基类对象引用调用,面积为:" << s.calArea() << endl; } int main() { // 定义Triangle、Rectangle、Square、Circle类的对象 double b, h, l, w, s, r; cout << "请输入三角形的底和高:" << endl; cin >> b >> h; Triangle tri(b, h); cout << "请输入矩形的长和宽:" << endl; cin >> l >> w; Rectangle rec(l, w); cout << "请输入正方形的边长:" << endl; cin >> s; Square squ(s); cout << "请输入圆形的半径:" << endl; cin >> r; Circle cir(r); // 分别调用fun函数输出各种图形的面积 cout << "计算三角形面积:" << endl; fun(&tri); fun(tri); cout << "计算长方形面积:" << endl; fun(&rec); fun(rec); cout << "计算正方形面积:" << endl; fun(&squ); fun(squ); cout << "计算圆形面积:" << endl; fun(&cir); fun(cir); return 0; } ``` 运行结果: ``` 请输入三角形的底和高: 5 7 请输入矩形的长和宽: 4 5 请输入正方形的边长: 6.7 请输入圆形的半径: 3.4 计算三角形面积: 通过基类指针调用,面积为:17.5 通过基类对象引用调用,面积为:17.5 计算长方形面积: 通过基类指针调用,面积为:20 通过基类对象引用调用,面积为:20 计算正方形面积: 通过基类指针调用,面积为:44.89 通过基类对象引用调用,面积为:44.89 计算圆形面积: 通过基类指针调用,面积为:36.3168 通过基类对象引用调用,面积为:36.3168 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值