c++ - 功能:声明/定义和通过值/引用传递参数
问题描述
我正在阅读C++ 初学者书中关于函数的一章,并且有两个问题。
1)函数应该在代码的开头声明并在末尾定义还是应该在开头完全定义函数?
#include <iostream>
void myfunction(); // function declaration
int main(){}
// function definition
void myfunction() {std::cout << "Hello World from a function.";}
或者
#include <iostream>
void myfunction() {std::cout << "Hello World from a function.";}
int main(){}
直觉上,我会使用最后一个变体,因为它更紧凑。是否有充分的理由为什么应该使用第一个(更长的)变体?
2)何时应将函数的参数用作值或引用?我看不出将参数用作参考应该有什么优势。
#include <iostream>
void myfunction(int& byreference)
{
byreference++; // we can modify the value of the argument
std::cout << "Argument passed by reference: " << byreference;
}
int main()
{
int x = 123;
myfunction(x);
}
如果我改用myfunction(int byreference),我会得到完全相同的结果。因此,如果我将参数作为值传递,我仍然可以修改它。
解决方案
关于什么时候定义函数,这取决于。我喜欢在顶部声明并在底部定义,因为如果定义很长,您不必滚动很多即可到达主函数。但这真的取决于你的喜好
当你通过值传递时,你给函数一个对象的副本。当你通过引用传递时,你给了对象一个引用。
// The original x wont chance
void foo(int x) {
x++;
}
// Will increment x by 1
void bar(int &x) {
x++;
}
所以如果要修改对象,可以通过引用传递。
如果你不想复制它,(像向量、字符串等的东西)你可以通过 const 引用传递它。
void baz(const SomeBigObject& o) {
/*
Define your function here
*/
}