1 引用作为函数形参
#include <cstdlib>
#include <iostream>
using namespace std;
struct teacher{
int id;
char name[64];
};
int getmem_1(teacher** t)
{
teacher* temp = NULL;
temp = (teacher*)malloc(sizeof(teacher));
if(temp == NULL)
return -1;
temp->id = 100;
strcpy(temp->name, "abc");
*t = temp;
return 0;
}
int freemem_1(teacher** t)
{
teacher* temp = *t;
if(temp == NULL)
return -1;
free(temp);
*t = NULL;
return 0;
}
int getmem_2(teacher* & t)
{
t = (teacher*)malloc(sizeof(teacher));
if(t == NULL)
return -1;
t->id = 100;
strcpy(t->name, "abc");
return 0;
}
int freemem_2(teacher* & t)
{
if(t == NULL)
return -1;
free(t);
t = NULL;
return 0;
}
int main(int argc, char *argv[])
{
teacher* t = NULL;
getmem_1(&t);
cout << "name: " << t->name << " id: " << t->id << endl;
freemem_1(&t);
getmem_2(t);
cout << "name: " << t->name << " id: " << t->id << endl;
freemem_2(t);
system("PAUSE");
return EXIT_SUCCESS;
}
比较指针与引用的区别,引用的使用明显要比指针使用方法简单一些,不容易出错。
2 引用作为函数返回值
#include <cstdlib>
#include <iostream>
using namespace std;
struct teacher{
int id;
char name[64];
};
teacher g_t = {
100,
"abc"
};
teacher& get_id(void)
{
return g_t;
}
int main(int argc, char *argv[])
{
cout << g_t.id << endl;
get_id().id = 20;
cout << g_t.id << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
引用作为函数的返回值,需要注意的是不能将局部变量作为引用返回;