标签:函数的重载
一、普通函数的重载
# include<iostream> using namespace std; void func(int); void func(float); void func(double); int main() { int a=4; float b=3.1; double c=3.1234; cout<<"a的值为:"<<a<<endl; cout<<"b的值为:"<<b<<endl; cout<<"c的值为:"<<c<<endl; cout<<"a的平方为:"; func(a); cout<<"b的平方为:"; func(b); cout<<"c的平方为:"; func(c); //我们可以将一个相同名字但是不同类型的函数,重复调用多次,来处理不同类型的数据 return 0; } void func(int i) { cout<<i*i<<endl; } void func(float i) { cout<<i*i<<endl; } void func(double i) { cout<<i*i<<endl; }
二、成员函数的重载
# include<iostream> using namespace std; class cube { public: void sum(); void sum(int i,int j); private: int x; int y; }; int main() { cube a; a.sum(2,3); a.sum(); return 0; } void cube::sum() { cout<<"x的立方为:"<<x*x*x<<"\t"<<"y的立方为:"<<y*y*y<<endl; } void cube::sum(int i,int j) { x=i; y=j; cout<<"x的值为:"<<x<<"\t"<<"y的值为:"<<y<<endl; }
三、构造函数的重载
# include<iostream> using namespace std; class rectangel { public: rectangel(){cout<<"构造一个长方形a!\n";} rectangel(int l,int w){length=l;width=w;cout<<"长方形的面积为:"<<length*width<<endl;} rectangel(int l,int w,int h){length=l;width=w;height=h;cout<<"长方形的体积为:"<<length*width*height<<endl;} private: int length; int width; int height; }; int main() { rectangel a; rectangel b(3,4); rectangel c(3,4,5); return 0; }
标签:函数的重载
原文地址:http://blog.csdn.net/cyksky/article/details/42215237