任何函数都能重载。
一、普通函数的重载
C语言中一个函数只能处理一个类型的数据,不可能兼顾两种或多种数据类型;C++使用使用同一名称的函数来处理多个类型的数据。
#include <iostream> #include <vector> using namespace std; double sq(double y) //fun1 { return y*y; } int sq(int y) //fun2 { return y*y; } double sq(int y) //fun3 { return (double)y*y; } void main() { int i=5; double d=5.5; cout<<sq(i)<<endl; cout<<sq(d)<<endl; }
其中的fun2和fun3冲突,因为两者的参数列表相同,不满足重载的条件。如果删掉fun3,得到答案25和30.25
所以,重载的依据是参数列表。
二、构造函数的重载
#include <iostream> using namespace std; class A { int a, b; public: A( ); A(int i, int j); ~A( ); void Set(int i, int j) {a=i; b=j;} }; A::A( ) { a=b=0; cout<<"No_arg_cons: a="<<a<<", b="<<b<<endl; } A::A(int i, int j) { a=i; b=j; cout<<"Constructor: a="<<a<<", b="<<b<<endl; } A::~A( ) { cout<<"Destructor: a="<<a<<", b="<<b<<endl; } void main( ) { cout<<"Starting first round:\n"; A obja[3]; for(int i=0; i<3; i++) obja[i].Set(i, i+1); cout<<"Finishing first round:\n"; cout<<"Starting second round:\n"; A objb[3]={A(5,6),A(7,8),A(9,10)}; cout<<"Finishing second round.\n"; cout<<"Program being terminated!\n"; } Result:Starting first round: No_arg_cons: a=0, b=0 No_arg_cons: a=0, b=0 No_arg_cons: a=0, b=0 Finishing first round: Starting second round: Constructor: a=5, b=6 Constructor: a=7, b=8 Constructor: a=9, b=10 Finishing second round. Program being terminated! Destructor: a=9, b=10 Destructor: a=7, b=8 Destructor: a=5, b=6 Destructor: a=2, b=3 Destructor: a=1, b=2 Destructor: a=0, b=1
三、运算符重载
在面向对象程序设计语言中,运算符也是一种函数,所以运算符也能像函数一样给予重载,以便完成更多功能。
运算符重载有两种实现方式,一种作为友元函数,另一种是成员函数。
1.友元函数方式
#include <iostream> using namespace std; class point { int x, y; public: point (int vx=0, int vy=0) { x = vx; y = vy; } friend point operator + (point & p1, point & p2); friend point operator - (point & p1, point & p2); void print() { cout<<x<<" "<<y<<endl; } }; point operator +(point & p1, point & p2) { point p; p.x = p1.x + p2.x; p.y = p1.y + p2.y; return p; } //不能返回[局部变量的]引用 point operator -(point & p1, point & p2) { point p; p.x = p1.x - p2.x; p.y = p1.y - p2.y; return p; } void main() { point p1(10,10),p2(20,20); p1.print(); p1 = p1 + p2; //即p1= operator + (p1, p2) p1.print(); p2 = p1 - p2; //即p2= operator - (p1, p2) p2.print( ); }
2.成员函数方式
#include <iostream> using namespace std; class point { int x, y; public: point() { x = 0; y = 0; } point (int vx, int vy) { x = vx; y = vy; } point operator + (point & p); point operator - (point & p); void print() {cout<<x<<" "<<y<<endl; } }; point point::operator +(point & p) { point temp; temp.x = x + p.x; //就是temp.x = this->x + p.x;两者相加 temp.y = y + p.y; return temp; } point point::operator -(point & p) { point temp; temp.x = x - p.x; temp.y = y - p.y; return temp; } void main() { point p1(10,10), p2(20,20), p3; p3.print(); p3 = p1 + p2; //即p3 = p1.operator + (p2); p3.print(); p3 = p3 - p1; //即p3 = p3.operator - (p1); p3.print(); }
25
30.25
时间: 2024-10-04 23:45:43