• C++语言程序化设计——第五次作业


    C++语言程序化设计——第五次作业

    第八章 多态性

    一、多态的概念

    1、多态的类型:重载多态、强制多态、包含多态和参数多态
    2、多态从实现的角度划分——编译时的多态、运行时的多态
    绑定工作在编译连接阶段完成的情况称为静态绑定,绑定工作在程序运行阶段完成的情况称为动态绑定。

    二、重载

    运算符重载的规则:
    (1)只能重载C++中已经有的运算符
    (2)重载之后的运算符的优先级和结合性都不会变
    (3)重载功能应当与原有功能类似

    赋值运算符重载实例:

    #include <iostream>
    using namespace std;
    
    class Cperson
    {
    public:
    
        Cperson():_age(0),_weight(0)
        {
        }
    
        void operator = (int age)//赋值运算符重载
        {
            this->_age = age;
        }
        void operator = (double weight)//赋值运算符重载
        {
            this->_weight = weight;
        }
    
        void show()
        {
            cout << "age = " << _age << endl;
            cout << "weight = " << _weight << endl;
        }
    private:
        int _age;
        double _weight;
    };
    
    
    int main()
    {
        Cperson per1;
        per1 = 23;
        per1 = 68.12;
        per1.show();
    
        system("pause");
        return 0;
    }
    

    运行结果:

    三、虚函数

    虚函数是动态绑定的基础。虚函数经过派生之后,在类族中就可以实现运行过程中的多态。

    代码实例:

    #include<iostream>
    #include<algorithm>
    using namespace std;
    class Shape
    {
    public:
        virtual double area()//虚函数
        {
            return 1.00;
        }
    };
    class Circle :public Shape
    {
        double r;
    public:
        Circle(double d) :r(d) {};
        double area()//覆盖基类的虚函数
        {
            return 3.1415926*r*r;
        }
    };
    class Square :public Shape
    {
        double length;
    public:
        Square(double l) :length(l) {};
        double area()//覆盖基类的虚函数
        {
            return length * length;
        }
    };
    class Rectangle :public Shape
    {
        double length, height;
    public:
        Rectangle(double l, double h) :length(l), height(h) {};
        double area()//覆盖基类的虚函数
        {
            return length * height;
        }
    };
    
    int main()
    {
        Shape *p;
        double result = 0;
        Circle c(3);
        Square s(12.2);
        Rectangle r(2.3, 5);
    
        p = &c; result += p->area();
        p = &s; result += p->area();
        p = &r; result += p->area();
        
        cout << "总面积为:" << result << endl;
        system("pause");
        return 0;
    }
    

    运行结果:

  • 相关阅读:
    ASP.NET2.0中GridView加入CheckBox实现全选!
    恢复误删数据(SQL Server 2000)--Log Explorer
    url传递中文的解决方案总结
    JavaScript : Tip提示框。
    合并GridView中某列相同信息的行
    ASP.NET 2.0服务器控件与form runat=server标记 !!
    实现天气预报类···························
    正则抓取SINA天气预报数据!!!
    ASP.NET 2.0中将 GridView 导出到 Excel 文件中
    GridView控件修改、删除示例(修改含有DropDownList控件)
  • 原文地址:https://www.cnblogs.com/ningningning/p/11749816.html
Copyright © 2020-2023  润新知