C/C++语言是一种通用的编程语言,具有高效、灵活和可移植等特点。C语言主要用于系统编程,如操作系统、编译器、数据库等;C语言是C语言的扩展,增加了面向对象编程的特性,适用于大型软件系统、图形用户界面、嵌入式系统等。C/C++语言具有很高的效率和控制能力,但也需要开发人员自行管理内存等底层资源,对于初学者来说可能会有一定的难度。
普通变量引用: 引用的实质就是取别名,&写到等号左侧叫引用,写到等号右侧叫取地址.
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) { int x = 10;
int &tmp = x; int *ptr = &x;
cout << "tmp => "<< &tmp << endl; cout << "x => "<< &x << endl; cout << "ptr => " << ptr << endl;
system("pause"); return 0; }
|
普通数组引用: 普通数组应用指针类型。
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) { int Array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int(&p_array)[10] = Array;
for (int x = 0; x < 10; x++) cout << p_array[x] << " ";
typedef int(type_array)[10]; type_array &type_ptr = Array; for (int x = 0; x < 10; x++) cout << type_ptr[x] << " ";
system("pause"); return 0; }
|
向函数中传递引用: 参数传递3种方式,传递数值,传递地址,还可以传递引用.
#include <iostream>
using namespace std;
void MySwap(int &x, int &y) { int tmp = x; x = y; y = tmp; cout << "MySwap ==> x = " << x << endl; }
void MySwap_PTR(int *x, int *y) { int tmp = *x; *x = *y; *y = tmp; cout << "MySwap_PTR ==> x = " << *x << endl; }
int main(int argc, char* argv[]) { int x = 10; int y = 20; cout << "x = " << x << endl; MySwap(x, y); cout << "x = " << x << endl;
system("pause"); return 0; }
|
返回引用的函数: 将一个函数定义为可引用的类型,可在表达式内使用左值引用。
#include <iostream>
using namespace std;
int & dowork() { int x = 10; cout << "x = " << x << endl; return x; }
int main(int argc, char* argv[]) { int &ret = dowork();
cout << ret << endl; cout << ret << endl;
dowork() = 1000; int re_ret = dowork() = 1000; cout << re_ret << endl;
system("pause"); return 0; }
|
定义常量引用: 常量引用一般情况下不可修改,但是我们可以通过分配新的内存的方式强行修改它.
#include <iostream>
using namespace std;
int dowork() { const int &ref = 100;
int *ptr = (int*)&ref; *ptr = 2000;
return ref; }
int do_work(const int &val) { int *ptr = (int*)&val; *ptr = 1000; return val; }
int main(int argc, char* argv[]) { int ret = dowork(); cout << ret << endl;
int ret_val = do_work(10); cout << ret_val << endl;
system("pause"); return 0; }
|
定义指针引用: 通过指针的方式引用函数。
#include <iostream>
using namespace std;
struct Person { int m_age; };
void allocat(Person **ptr) { *ptr = (Person *)malloc(sizeof(Person)); (*ptr)->m_age = 100; }
void allocatByref(Person* &ptr) { ptr = (Person *)malloc(sizeof(Person)); ptr->m_age = 1000; }
int main(int argc, char* argv[]) { struct Person *ptr = NULL; allocat(&ptr); cout << "ptr --> " << ptr->m_age << endl;
Person *ptr_byref = NULL; allocatByref(ptr_byref); cout << "ptr_byref --> " << (*ptr_byref).m_age << endl;
system("pause"); return 0; }
|