首页 > 编程语言 > 详细

C++中的多态

时间:2014-03-24 06:25:19      阅读:495      评论:0      收藏:0      [点我收藏+]

多态性是面向对象程序设计的重要特征之一。多态性是指发出同样的消息被不同类型的对象接收时有可能导致完全不同的行为。

多态的实现方式包括以下3种:函数重载、运算符重载、虚函数。

1、运算符重载:

bubuko.com,布布扣
 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Complex
 5 {
 6 private:
 7     int real,imag;
 8 public:
 9     void show() const;
10     Complex operator +(const Complex c);
11     Complex operator -(const Complex c);
12     /*
13     Complex(int a=0,int b=0)
14     {
15         real=a;imag=b;
16     }
17     */
18     Complex(int a=0,int b=0):real(a),imag(b)
19     {}
20 };//don‘t forget this!
21 
22 void Complex::show() const
23 {
24     cout<<"real:"<<real<<"imag:"<<imag<<endl;
25 }
26 
27 Complex Complex::operator +(const Complex c)
28 {
29     Complex ret;
30     ret.real=real+c.real;
31     ret.imag=imag+c.imag;
32     return ret;
33 }
34 
35 Complex Complex::operator -(const Complex c)
36 {
37     Complex ret;
38     ret.real=real-c.real;
39     ret.imag=imag-c.imag;
40     return ret;
41 }
42 
43 int main()
44 {
45     Complex a(2,3),b(-1,5),c,d;
46     a.show();
47     b.show();
48     c=a+b;
49     d=a-b;
50     c.show();
51     d.show();
52     return 0;
53 }
bubuko.com,布布扣

注意运算符重载操作数个数:重载为类的成员函数时,参数个数=原操作数个数-1(后置++、--除外);重载为非成员函数时,参数个数=原操作数个数,且至少有一个自定义类型。

C++中的多态,布布扣,bubuko.com

C++中的多态

原文:http://www.cnblogs.com/kekewuling/p/3619870.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!