C++ 函数

2018-03-24 16:44 更新

学习C++ - C++函数

以下代码显示如何创建函数。


#include <iostream> 
using namespace std; 
void my_function(int);    // function prototype for my_function() 

int main() { 
    my_function(3);       // call the my_function() function 
    cout << "Pick an integer: "; 
    int count; 
    cin >> count; 
    my_function(count);   // call it again 
    cout << "Done!" << endl; 
    return 0; 
} 

void my_function(int n)   // define the my_function() function 
{ 
    using namespace std; 
    cout << "Hi:" << n << " ." << endl; 
    // void functions don"t need return statements 
}

main()函数调用my_function()函数两次,一次参数为3,一次为变量参数。

上面的代码生成以下结果。

定义函数

没有返回值的函数称为类型void函数,并具有以下一般形式:

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

parameterList设置传递给函数的参数的类型和数量。

可选的return语句标记函数的结尾。

通常,您使用void函数执行某种操作。

具有返回值的函数产生返回给调用者的值。

这样的函数被声明为具有与返回的值相同的类型。这是一般的形式:

typeName functionName(parameterList) { 
   statements 
   return value;   // value is type cast to type typeName 
} 

函数原型

要使用C ++函数,您必须提供函数定义,提供函数原型和调用函数。


#include <iostream>
using namespace std;
void simple();    // function prototype

int main()
{
    
    cout << "main() will call the simple() function:\n";
    simple();     // function call
  cout << "main() is finished with the simple() function.\n";
    return 0;
}
// function definition
void simple()
{
    cout << "a function.\n";
}

上面的代码生成以下结果。

函数头

列表2.5中的my_function()函数有这个头:

void my_function(int n)

最初的void表示my_function()没有返回值。

所以调用my_function()不会产生一个可以分配给main()中的变量的数字。

因此,第一个函数调用如下所示:

my_function(3);            // ok for void functions 

因为my_function()缺少一个返回值,所以你不能这样使用:

simple = my_function(3);   // not allowed for void functions 

括号内的int n表示您希望使用带有int类型的单个参数的my_function()。

n是一个新变量,分配了在函数调用期间传递的值。

以下函数调用将值3赋值给my_function()头中定义的n变量:

my_function(3);

当函数体中的cout语句使用n时,它使用函数调用中传递的值。

具有返回值的用户定义函数

以下代码显示如何转换值。


#include <iostream> 

int convert(int);     // function prototype 
int main() { 
     using namespace std; 
     int input; 
     cout << "Enter the weight: "; 
     cin >> input; 
     int pounds = convert(input); 
     cout << input << " input = "; 
     cout << pounds << " pounds." << endl; 
     return 0; 
} 

int convert(int sts) 
{ 
      return 14 * sts; 
} 

在main()中,程序使用cin为整数变量输入提供一个值。

此值作为参数传递给convert()函数。

上面的代码生成以下结果。

在多功能程序中使用指令

要使std命名空间可用于这两个函数,请将指令放在两个函数之外和之上:


#include <iostream> 
using namespace std; // affects all function definitions in this file 
void my_function(int); 

int main() { 
     my_function(3); 
     cout << "Pick an integer: "; 
     int count; 
     cin >> count; 
     my_function(count); 
     cout << "Done!" << endl; 
     return 0; 
} 

void my_function(int n) 
{ 
     cout << "my_function says touch your toes " << n << " times." << endl; 
} 

上面的代码生成以下结果。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号