【C++】学习笔记二十九——函数

来源:互联网 发布:扎克拉文体测数据 手掌 编辑:程序博客网 时间:2024/06/05 06:44

函数

  • 函数定义
  • 函数原型
  • 调用函数

程序7.1

#include<iostream>void simple();              //函数原型int main(){    using namespace std;    cout << "main() will call the simple() function:\n";    simple();           //函数调用    cout << "main() is finished with the simple() function.\n";    system("pause");    return 0;}//函数定义void simple(){    using namespace std;    cout << "I'm but a simple function.\n";}

定义函数

没有返回值的函数称为void()函数:

void functionName(parameterList){    statement(s)    return;                //可选}

有返回值的函数:

typeName functionName(parameterList){    statements    return value;}

C++对于返回值的类型有一定的限制:不能是数组。但可以是其它任何类型——整数、浮点数、指针、结构、对象;(C++虽然不能直接返回数组,但可以将数组作为结构或对象的组成部分来返回。)

如果函数包含多条返回语句,则在遇到第一条返回语句后结束。


函数原型和函数调用

#include<iostream>void cheers(int);double cube(double x);int main(){    using namespace std;    cheers(5);    cout << "Give me a number: ";    double side;    cin >> side;    double volume = cube(side);    cout << "A " << side << "-foot cube has a volume of ";    cout << volume << " cubic feet.\n";    cheers(cube(2));    system("pause");    return 0;}void cheers(int n){    using namespace std;    for (int i = 0; i < n; i++)        cout << "Cheers! ";    cout << endl;}double cube(double x){    return x*x*x;}

函数原型描述了函数到编译器的接口,也就是说,它将函数返回值的类型以及参数的类型和数量告诉编译器。函数原型是一条语句,因此必须以分号结尾。函数原型的参数列表中可以包括变量名,也可以不包括。

0 0