c++ 教程:函数的使用
大约 5 分钟
函数定义(Function Declarations)
- ✔ 隐藏功能实现细节
- ✔ 避免为常见任务重复编写代码
- ✔ 将问题分解为单独的功能,更容易测试
示例
double mean (double a, double b) { return (a + b) / 2; }
int main () { std::cout << mean(2, 6) <<'\n'; // prints 4 return 0; }
返回值(Return Types)
有返回值
double square (double x) { return (x * x); } int max (int x, int y) { if (x > y) return x; else return y; }
无返回值
void print_squares (int n) {
for (int i = 1; i <= n; ++i)
cout << square(i) << '\n';
}
Attribute [[nodiscard]]
[[nodiscard]] bool prime (int i) { … }
// return value(s) used: bool const yes = prime(47); ✔ if (prime(47)) { … }
// return value discarded/ignored: prime(47); // COMPILER WARNING
不要返回局部变量的引用
double& square (double x) { double r = (x * x); return r; }
int main () { double r = square(3); // Undefined Behavior return 0; }
参数(Parameters)
常量参数(const Parameters)
int foo (int a, int const b) { a += 5; // ✔ b += 10; // ✖ COMPILER ERROR: can't modify const parameter return (a + b); }
// calling foo: foo(2,9); // const has no effect here
常量引用参数(const Reference Parameters)
✖ pass by value ⇒ copy ✔ pass by const& ⇒ no copy
int median (vector <int>); int median (const vector <int> &); auto v = get_samples("huge.dat"); auto v = get_samples("huge.dat"); auto m = median(v); auto m = median(v); // runtime & memory overhead! // no copy ⇒ no overhead!
默认参数(default Parameters)
double f (double a, double b = 1.5) { return (a * b); }
int main () { cout << f(2); // 1 argument → 3.0 cout << f(2, 3); // 2 arguments → 6.0 }
void foo (int i = 0); ✔ void foo (int n, double x = 2.5); ✔ void foo (int a, int b = 1, float c = 3.5f); ✔ void foo (int a, int b = 1, int c ); ✖
❗ 在第一个默认参数之后的每个参数都必须是默认参数!