1. 指向指针的引用
#include <cstdlib> #include <iostream> using namespace std; // int *&lhs 的定义应该从右向左理解: // lhs 是一个引用,与指向 int 的指针相关联。 // 也就是说,lhs 是传递进 ptrswap 函数的指针的别名。 // 注意:不能这样定义:int &*lhs,编译报错提示为:cant declare pointer to “int &” void ptrswap( int *&lhs, int *&rhs ) { int *tmp = lhs; lhs = rhs; rhs = tmp; } int main(int argc, char *argv[]) { int i = 10; int j = 20; int *pi = &i; int *pj = &j; std::cout<<"before swap: *pi == "<<*pi<<"; *pj =="<<*pj <<";" <<std::endl; ptrswap(pi,pj); std::cout<<"after swap: *pi == "<<*pi<<"; *pj =="<<*pj <<";" <<std::endl; system("PAUSE"); return EXIT_SUCCESS; }
2 . 指向指针的指针
#include <cstdlib> #include <iostream> using namespace std; void ptrswap( int **lhs, int **rhs ) { int *tmp = *lhs; *lhs = *rhs; *rhs = tmp; } int main(int argc, char *argv[]) { int i = 10; int j = 20; int *pi = &i; int *pj = &j; std::cout<<"before swap: *pi == "<<*pi<<"; *pj =="<<*pj <<";" <<std::endl; ptrswap(&pi,&pj); std::cout<<"after swap: *pi == "<<*pi<<"; *pj =="<<*pj <<";" <<std::endl; system("PAUSE"); return EXIT_SUCCESS; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-29 03:14:33