引用变量:
int rats = 101;//声明rats为101
int * pt = &rats;//指针pt指向rats的内存地址
int & rodents = *pt;//
int bunnies = 50;
pt = &bunnies;
#include <iostream>
using namespace std;
void swapr(int & a, int & b);
void swapp(int * p, int * q);
void swapv(int a, int b);
int main()
{
int wallet1 = 300;
int wallet2 = 350;
cout << "wallet1 = " << wallet1<<endl;
cout << "wallet2 = " << wallet2<<endl;
cout << "using references to swap contents:\n";
swapr(wallet1, wallet2);
cout << "wallet1 = " << wallet1 << endl;
cout << "wallet2 = " << wallet2 << endl;
cout << "using point to swap contents:\n";
swapp(&wallet1,&wallet2);
cout << "wallet1 = " << wallet1 << endl;
cout << "wallet2 = " << wallet2 << endl;
cout << "using value to swap contents:\n";
swapv(wallet1, wallet2);
cout << "wallet1 = " << wallet1 << endl;
cout << "wallet2 = " << wallet2 << endl;
getchar();
return 0;
}
void swapr(int & a, int & b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swapp(int * p, int * q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
void swapv(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
上述代码中,三个子函数都为void函数,前两者通过引用于指针将wallet1和2的值改变了,swapr函数在运行的时候子函数中的wallet针对的地址就是main函数中wallet的地址,所以可能成功对wallet的值进行修改,swapp函数也是一样,但是在swapv函数中则不是一样,wallet作为参数进入swapv函数意味着仅仅将值赋给swapv函数的形参a和b,可以如此理解swapv(wallet1,wallet2)=swapv(a=wallet1=300,b=wallet2=350)。
#include <iostream>
using namespace std;
double cube(double a);
double refcube(double &ra);
int main()
{
double x = 3.0;
cout << cube(x) << " = cube of " << x << endl;
cout << refcube(x) << " = cube of " << x << endl;
getchar();
return 0;
}
double cube(double a)
{
a = a * a * a;
return a;
}
double refcube(double &ra)
{
ra *= ra * ra;
return ra;
}
请注意更新C++版本,老版本的编译环境可能导致refcube函数无法对x的值进行修改。
int main()
{
sysop looper =
{
"rick \"fortran\"looper",
"I'm a goto kind of guy.",
0
};
use(looper);
cout << "looper:" << looper.used << "use(s)\n";
sysop copycat;
copycat = use(looper);
cout << "looper:" << looper.used << "use(s)\n";
cout << "copycat:" << copycat.used << "use(s)\n";
getchar();
return 0;
}
const sysop & use(sysop & sysopref)//返回sysop结构
//(sysop & sysopref)表示sysopref作为sysop的引用,在use函数里面代表sysop
{
cout << sysopref.name << "says:\n";
cout << sysopref.quote << endl;
sysopref.used++;
return sysopref;
}
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int Arsize = 80;
char * left (const char * str, int n = 1);
int main()
{
char sample[Arsize];
cout << "enter a string: \n";
cin.get(sample, Arsize);
char *ps = left(sample, 4);
cout << ps << endl;
delete[] ps;
ps = left(sample);//默认第二个参数为int n = 1
cout << ps << endl;
getchar();
getchar();
return 0;
}
char * left(const char * str, int n)
{
if (n < 0)
{
n = 0;
}
char * p = new char[n + 1];
int i;
for (i = 0; i < n && str[i]; i++)//第二部分&&两侧只要有一侧为false,整个表达式就为false
//与&的区别就是&当左侧为负之后就不再计算右侧
//在此处表达的意思是当i>=n或者str[i]为空值,该表达式false
{
p[i] = str[i];
}
while (i <= n) //当i=4时,进入while循环
{
p[i++] = '\0';//先执行p[i]=‘\0’,然后再执行i++
}
return p;
}