Created
August 1, 2022 03:23
-
-
Save 1000copy/f6cb54994dee20bd38ae438de2860f23 to your computer and use it in GitHub Desktop.
valueVSrefVSpointer.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <assert.h> | |
void swap(int a, int b) { | |
int c = a; | |
a = b; | |
b = c; | |
assert(a == 1 && b == 0); | |
} | |
void swap_pointer(int* a, int* b) { | |
int c = *a; | |
*a = *b; | |
*b = c; | |
} | |
void swap_ref(int& a, int& b) { | |
int c = a; | |
a = b; | |
b = c; | |
} | |
int main(){ | |
int a = 0; | |
int b = 1; | |
assert(a == 0 && b == 1); | |
swap(a, b); | |
assert(a == 0 && b == 1); | |
swap_pointer(&a, &b); | |
assert(a == 1 && b == 0); | |
swap_ref(a, b); | |
assert(a == 0 && b == 1); | |
} | |
//RECT rect; | |
//GetWindowRect(hwnd, &rect); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
变量名实质上是一段连续内存空间的别名,程序中通过变量来申请并命名内存空间,通过变量的名字可以使用存储空间
对一段连续的内存空间只能取一个别名吗?
c++中新增了引用的概念,引用可以作为一个已定义变量的别名。
通过引用参数产生的效果同按地址传递是一样的。引用的语法更清楚简单:
当引用被用作函数参数的时,在函数内对任何引用的修改,将对还函数外的参数产生改变。