// testHellloworld2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class man
{
public:
char name[100];
public :
int age;
int sex;
};
int _tmain(int argc, _TCHAR* argv[])
{
// const int i =0;
//i=5;不可更改
// void *p;
// int *i = (int *)p; //类型转换必须强制转换
// int *p = (int *)malloc(sizeof(int));//分配内存
// *p = 10;
// free(p); //释放内存
// int *p = new int; //分配内存 int *p = new int(10);直接赋值
// *p = 10;
// cout << *p << endl;
// delete p; //释放内存
int *p = new int[10];
for(int i=0;i<10;i++)
{
p[i]=i;
}
for(int i=0;i<10;i++)
{
cout << p[i] << endl;
}
delete []p; //释放内存
/** man m;
strcpy_s(m.name,"tom" );
m.age = 20;
m.sex =1;
cout << m.name<<m.age <<endl; */
getchar();
return 0;
}
内联函数inline
// testHellloworld2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//inline内联函数:内联函数不作为函数调用,而是直接吧内联函数的代码嵌入到调用的语句中
//内联函数适合函数代码很少,并且频繁的大量调用
inline int mymax(int a,int b)
{
if(a>b)
return a;
return b;
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i=0;i<100;i++)
{
int a = mymax(i,10);
cout << a <<endl;
}
getchar();
return 0;
}
引用:就是一个变量的别名,而不是地址
引用做为函数的参数,没有出栈,入栈操作,所以效率更高
如果要使引用参数的值不能在函数内部被修改,那么就定义为常量引用 const &
// testHellloworld2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//引用
void myswap(int &a,int &b)
{
int temp =a;
a=b;
b=temp;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a=10;
int b=20;
int &c=a;//c就是a的别名,,引用必须即刻赋值
myswap(a,b); //传值:被调函数参数:用&引用
cout<< "a="<< a <<endl;
cout<< "b="<< b <<endl;
getchar();
return 0;
}
C++允许在定义的时候,提供缺省参数,如果调用函数的时候没有提供形参,那么形参对的值就是缺省值。
// testHellloworld2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//引用
void func(int a = 10)
{
printf("a = %d",a);
}
int _tmain(int argc, _TCHAR* argv[])
{
func();
getchar();
return 0;
}
模板函数:
// testHellloworld2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//模板函数
template <class T>
T myadd(T a,T b)
{
return a + b;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a = 1;
int b= 2;
myadd(a,b);
cout<< myadd(a,b) <<endl;
getchar();
return 0;
}
函数的重载:
函数的名称是一样的,但参数不同可以重载
函数参数相同,但返回值不同,不可以重载
命名空间namespace:
// testHellloworld2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//命名空间
namespace zhujy{
void func(int i)
{
cout<< "zhujy func" <<endl;
}
}
namespace zhujy22{
void func(int i)
{
cout<< "zhujy func22" <<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
zhujy::func(10);
zhujy22::func(10);
getchar();
return 0;
}