以下代码显示如何创建函数。
#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;
}
上面的代码生成以下结果。
C++ 嵌套 if 语句 C++ 判断在 C++ 中,嵌套 if-else 语句是合法的,这意味着您可以在一个 if 或 else if 语句内使用另一个 if 或...
C++ sizeof 运算符 C++ 运算符sizeof 是一个关键字,它是一个编译时运算符,用于判断变量或数据类型的字节大小。sizeof 运算符可...
C++ 指针数组 C++ 指针在我们讲解指针数组的概念之前,先让我们来看一个实例,它用到了一个由 3 个整数组成的数组:#include ios...
C++ 类构造函数 & 析构函数 C++ 类 & 对象类的构造函数类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行...
C++ 下标运算符 [] 重载 C++ 重载运算符和重载函数下标操作符 [] 通常用于访问数组元素。重载该运算符用于增强操作 C++ 数组的功...