C++语言基础 例程 函数模板

贺老师的教学链接

使用用函数模板

#include <iostream>
using namespace std;
template<typename T>        //模板声明,其中T为类型参数
T max(T a,T b,T c)          //定义一个通用函数,用T作虚拟的类型名
{
    if(b>a) a=b;
    if(c>a) a=c;
    return a;
}

int main( )
{
    int i1=185,i2=-76,i3=567;
    double d1=56.87,d2=90.23,d3=-3214.78;
    long g1=67854,g2=-912456,g3=673456;
    cout<<"i_max="<<max(i1,i2,i3)<<endl; //调用模板函数,此时T被int取代
    cout<<"f_max="<<max(d1,d2,d3)<<endl; //调用模板函数,此时T被double取代
    cout<<"g_max="<<max(g1,g2,g3)<<endl; //调用模板函数,此时T被long取代
    cout<<"c_max="<<max('1','a','A')<<endl; //调用模板函数,此时T被long取代
    return 0;
}
时间: 2024-07-30 08:49:17

C++语言基础 例程 函数模板的相关文章

C++语言基础 例程 类模板

贺老师的教学链接  本课讲解 类模板的使用--参数化类 #include <iostream> using namespace std; template<class numtype> class Compare { public: Compare(numtype a,numtype b) { x=a; y=b; } numtype max( ) { return (x>y)?x:y; } numtype min( ) { return (x<y)?x:y; } pri

C++语言基础 例程 函数中的引用

贺老师的教学链接  本课讲解 引用作为形参 #include<iostream> using namespace std; class Sample { int x; public: Sample(int a): x(a) {cout<<"A";} Sample(Sample &a): x(a.x) {cout<<"B";} int getX(){return x;} }; void disp(Sample &s)

C++语言基础 例程 函数重载

贺老师的教学链接 重载函数:同名同体,但接口不同 #include <iostream> using namespace std; int max(int a,int b,int c); //函数声明 double max(double a,double b,double c); long max(long a,long b,long c); int main( ) { int i1,i2,i3,i; cin>>i1>>i2>>i3; //输入3个整数 i=

C++语言基础 例程 虚函数

贺老师的教学链接  本课讲解 指向基类的指针,为何只能访问来自基类成员?! #include <iostream> #include <string> using namespace std; //声明基类Student class Student { public: Student(int, string,float);//声明构造函数 void display( ); //声明输出函数 protected: //受保护成员,派生类可以访问 int num; string nam

C++语言基础 例程 内置函数

贺老师的教学链接 例:函数指定为内置函数 #include <iostream> using namespace std; inline int max(int,int,int); int main( ) { int i=10,j=20,k=30,m; m=max(i,j,k); cout<<"max="<<m<<endl; return 0; } inline int max(int a,int b,int c) { if(b>a

C++语言基础 例程 有默认参数的函数

贺老师的教学链接 形参/实参.声明/调用/定义 #include <iostream> using namespace std; int max(int a, int b, int c=0);//仅声明时设默认 int main( ) { int a,b,c; cin>>a>>b>>c; cout<<"max(a,b,c)="<<max(a,b,c)<<endl; cout<<"m

C++语言基础 例程 类声明和成员函数定义的分离

贺老师的教学链接  本课讲解 1.一个程序,一个源文件的做法 #include<iostream> #include<cstring> using namespace std; class Student { private: char Name[20]; //学生姓名 double Chinese; //语文成绩 double Math; //数学成绩 public: double Average( );//计算平均成绩 double Sum( ); //计算总分 void Sh

C++语言基础 例程 类的成员函数

贺老师的教学链接  本课讲解 分清"你我" #include <iostream> using namespace std; class Time { public: void set_time(int,int,int); void show_time(); private: int hour; int minute; int sec; }; int main( ) { Time t1,t2; t1.set_time(12,45,32); t2.set_time(21,32

C++语言基础 例程 重载流插入运算符和流提取运算符

贺老师的教学链接  本课讲解 重载流插入运算符"<<" #include <iostream> using namespace std; class Complex { public: Complex( ) { real=0; imag=0; } Complex(double r,double i) { real=r; imag=i; } Complex operator + (Complex &c2); //运算符"+"重载为成员函