1, register keyword
#include <iostream>
using namespace std;
int main()
{
register int a = 100;
&a; //C中不允许对寄存器变量取地址操作,但C++可以
return 0;
}
2, & quote (when the syntax appears strange)
#include <iostream>
using namespace std;
struct test
{
int &a; //当成指针来分析
char &b;
double &c;
};
int main()
{
int a = 1;
char b = 'm';
int &c = a;
char &d = b;
cout << sizeof(c) << endl; //不用关心编译器是怎么实现的(正常的语法现象)
cout << sizeof(d) << endl;
cout << sizeof(test) <<endl; //当分析奇怪的语法现象时,需要考虑具体的引用实现(常指针)。eg:char str[32] = {0}; str++ 常指针
}
3, reference & (local variable in the subroutine of - not in general, where the error analysis)
#include <stdio.h>
using namespace std;
int x = 100;
int &f()
{
//int x = 100; 不能返回局部变量的引用,函数结束后,栈释放空间。什么意思??变量a引用函数f();函数f()又引用局部变量x的值,函数调用开始时为x开辟4个字节里边存放100,调用结束后,栈释放空间, 而变量a的引用需要在整个程序开始直到结束,故需要定义一个全局变量x;
return x;
}
int main()
{
int &a =f();
return 0;
}
4, reference & (formal parameters in the subroutine)
#include <iostream>
#include <cstrlib>
using namespace std;
void Init(char *&ptr) //引用,在C中怕是得用二级指针来承接了
{
ptr = (char *)malloc(sizeof(char)); //在C中(*ptr)=...
}
int main()
{
char *str = NULL;
Init(str); //在C中Init(&str);
strcpy(str,"helloworld");
cout << str << endl;
}
5, reference & (constant / variable)
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int &b = a; //普通引用,变量初始化普通引用
//int &c = 100; //不能用常量初始化普通引用
const int &d = a; //变量a初始化常引用
//d++; //常引用不能被修改
const int &e = 100;//常量100初始化常引用,编译分配4个字节大小的内存并用100来填充
//e++; //常引用不能被修改
return 0;
}
6, the default parameters
#include <iostream>
using namespace std;
void f(int a, int b=100, int c=200) //一旦使用默认参数,从这个默认参数开始后边所有参数都使用默认参数
{
cout << a << b << c <<endl;
}
int main()
{
f(1,2);
return 0 ;
}
7, occupying parameters
#include <iostream>
using namespace std;
void f(int a,int b,int =0) //默认参数与占位参数结合使用
{
cout << a << b <<endl;
}
int main()
{
f(1,2);
return 0 ;
}
8, function overloading
function overloading criteria:
1, different types of parameter
2, a different sequence parameter
3, the number of different parameter, one of three conditions are satisfied to
the function return value is not overloaded as a function of the standard
#include <iostream>
using namespace std;
int f(int i,int j) //函数类型不同
{
}
float f(float i,float j)
{
}
void f(char a,int b) //函数顺序不同
{
}
void f(int b,char a)
{
}
/*float f(int i,int j)
{
} */ //函数返回值不同不作为函数重载的标准
int main()
{
int a =1;b=2;
float x=1.11,y=2.22
add(a,b);
add(x,y);
}
9, the function pointer and function overloading
#include <iostream>
using namespace std;
void f(int a,int b
{
cout << "helloworld" << endl;
}
void f(int a,int b,int c)
{
cout << "verygood" <<endl;
}
int main()
{
void (*p) (int ,int );
p =f;
p(1,2);
//p(1,2,3); //指针为俩参数
return 0;
}