4.10 本章实例--类的使用
前面介绍了继承、多态和重载的基本概念和使用方法。C++(www.cppentry.com)作为面向对象的程序设计语言,继承、多态和重载的出现使C++(www.cppentry.com)面向对象的特点体现的更加明确。本节给出几个例子。
【示例4.26】 创建复数类,利用运算符重载,实现其加法和减法。
- #include <iostream.h>
- class complex
- {
- public:
- complex(double xx = 0.0, double yy = 0.0)
- {x = xx;y = yy;}
- complex operator+(complex);
- complex operator-(complex);
- void show();
- private:
- double x;
- double y;
- };
- complex complex::operator+(complex b)
- {
- complex a;
- a.x = x+b.x;
- a.y = y+b.y;
- return a;
- }
- complex complex::operator-(complex b)
- {
- complex a;
- a.x = x-b.x;
- a.y = y-b.y;
- return a;
- }
- void complex::show()
- {
- if(y>=0)
- cout<<x<<"+"<<y<<"j"<<endl;
- else
- cout<<x<<y<<"j"<<endl;
- }
- void main()
- {
- complex a(1.1, 1.2);
- complex b(2.1, 2.2);
- complex c;
- c = a+b;
- cout<<"a = ";
- a.show();
- cout<<"b = ";
- b.show();
- cout<<"c = a+b =";
- c.show();
- c = a-b;
- cout<<"c = a-b =";
- c.show();
- }
程序输出如下所示。
- a=1.1+1.2j
- b=2.1+2.2j
- c=a+b=3.2+3.4j
- c=a-b=-1-1j
分析:上面介绍了一个使用运算符重载进行程序设计的例子。运算符重载可以实现编译时的多态性,也就是在编译阶段实现多态性的选择。运算符重载仅仅可以实现编译时的多态性,并不能在程序执行时进行多态性。下面的例子中将利用抽象类实现运行时的多态性。
【示例4.27】 创建抽象类circle,利用纯虚函数求解圆的内接正方形面积和周长。
- #include"iostream.h"
- class circle
- {
- public:
- void set(double x)
- {r=x;}
- virtual double area()=0;
- virtual double length()=0;
- protected:
- double r;
- };
- class square:public circle
- {
- public:
- double area()
- {return 2*r*r;}
- double length()
- {return 4*1.414*r;}
- };
- void main()
- {
- square op;
- op.set(2.68);
- cout<<"The area is: "<<op.area()<<endl;
- cout<<"The length is: "<<op.length()<<endl;
- }
分析:上面是抽象类的具体使用。对于一个拥有纯虚函数的抽象类来说,此虚函数在基类中没有定义,但它要求在派生类中去定义。上面程序的输出结果如下:
- The area is: 14.3648
- The length is: 15.1581
抽象类是一种特殊的类,它是为了抽象和设计的目的而建立的,它处于继承层次结构的较上层。抽象类是不能定义对象的,在实际中为了强调一个类是抽象类,可将该类的构造函数说明为保护的访问控制权限。
【责任编辑:
云霞 TEL:(010)68476606】