函数编程:从基础到应用
1. 指令程序介绍
指令程序的输出结果非常基础,只是几行文本,它们是某些游戏说明的开头。从输出结果来看,这个程序似乎早在之前就可以编写出来,但它背后有一个新元素——新函数。
你可以从相关网站(www.courseptr.com/downloads)下载该程序的代码,程序位于特定文件夹中,文件名是 instructions.cpp。以下是代码示例:
// Instructions
// Demonstrates writing new functions
#include <iostream>
using namespace std;
// function prototype (declaration)
void instructions();
int main()
{
instructions();
return 0;
}
// function definition
void instructions()
{
cout << "Welcome to the most fun you’ve ever had with text!\n\n";
cout << "Here’s how to play the game. . .\n";
}
2. 函数声明
在调用自己编写的函数之前,必须先声明它。一种声明函数的方法是编写函数原型,即描述函数的代码。编写原型时,先列出函数的返回值(如果函数不返回值则用 void),接着是函数名,然后是用括号括起来的参数列表。参数用于接收函数调用