为了看看这个,我写了这个简单的代码,我刚刚创建了不同类型的变量,并通过值,引用和指针将它们传递给函数:
int i = 1;
char c = 'a';
int* p = &i;
float f = 1.1;
TestClass tc; // has 2 private data members: int i = 1 and int j = 2
Run Code Online (Sandbox Code Playgroud)
函数体留空,因为我只是看看如何传入参数.
passByValue(i, c, p, f, tc);
passByReference(i, c, p, f, tc);
passByPointer(&i, &c, &p, &f, &tc);
Run Code Online (Sandbox Code Playgroud)
想知道数组的不同之处以及如何访问参数.
int numbers[] = {1, 2, 3};
passArray(numbers);
Run Code Online (Sandbox Code Playgroud)
部件:
passByValue(i, c, p, f, tc)
mov EAX, DWORD PTR [EBP - 16]
mov DL, BYTE PTR [EBP - 17]
mov ECX, …Run Code Online (Sandbox Code Playgroud) 在下面的代码中,
int firstFunction(int& refParam)
{
std::cout << "Type of refParam is: " << typeid(refParam).name() << '\n';
return refParam;
}
int secondFunction(int param)
{
std::cout << "Type of param is: " << typeid(param).name() << '\n';
return param;
}
int main()
{
int firstVar{ 1 };
int secondVar{ firstFunction(firstVar) };
int thirdVar{ secondFunction(firstVar) };
}
Run Code Online (Sandbox Code Playgroud)
控制台输出是
int
int
Run Code Online (Sandbox Code Playgroud)
当我检查Godbolt 链接中的汇编代码时。
firstFunction(int&):
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
mov eax, DWORD PTR [rax] …Run Code Online (Sandbox Code Playgroud)