您的位置:首页 > 编程语言 > C语言/C++

c++学习二

2015-06-03 12:21 381 查看
#include <iostream>

using  namespace std;

template<typename T>

T max(T a, T b, T c)

{
if(a > b) b = a;
if(c > b) return c;
return b;

}

void swap(int *p1, int *p2)

{
int *temp=(int *)malloc(sizeof(int));
//int *temp;//if directly use the temporary/iterim/extemporaneous/provisional variant to store some value, the compiler will give a error
//we can use the pointer which is not initialized to point a another address, it means if compiler or system not intialize the pointer temp,
// the pointer temp will have no space in system's memory, so you wouldn't store a data into the memory which you think to be owned by the temp
// but you can use temp to store a pointer, for example, temp = p1 will no error(p1 must be exist already and has its address), this is not to operate for memory, only variant itself

*temp = *p1;
*p1 = *p2;
*p2 = *temp;
free(temp);

}

void swap(int *p1, int *p2)

{// if we write the funciton as this above, we will not get the expected result, so we should know the value paased into the function is unidirectional, not

// bidirctional, so you can change the value of formal parameter, not to change the actual parameter, this is the reason why you cann't change the value of 

// a1 and b1
int *temp;
temp = p1;
p1 = p2;
p2 = temp;

}

int main(int argc ,char **argv)

{
char a[20]="l am a teacher";
int i1=185,i2=-76,i3=567,i;

   double d1=56.87,d2=90.23,d3=-3214.78,d;

   long g1=67854,g2=-912456,g3=673456,g;

   int a1, b1;

   int *point1, *point2;

   cin>>a1>>b1;

   point1 = &a1;

   point2 = &b1;

   if(a1 < b1 ) 
  swap(point1,point2);

   cout << "a1----"<<a1 << "---b1---"<< b1 <<endl;

   i=max(i1,i2,i3); //调用模板函数,此时T被int取代

   d=max(d1,d2,d3); //调用模板函数,此时T被double取代

   g=max(g1,g2,g3); //调用模板函数,此时T被long取代

   cout<<"i_max="<<i<<endl;

   cout<<"f_max="<<d<<endl;

   cout<<"g_max="<<g<<endl;

   cout<<"memory length--"<<sizeof(a)<<endl;

   cout<<"real length-----"<<strlen(a)<<endl;

   getchar();

     getchar();
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++