void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
该函数的名称是 displayMessage,意思是“显示消息”,它是一个描述性的名称,说明了函数的功能。函数就应该按这种方式命名,即通过名称揭示其功能。因为该函数不需要接收任何信息以执行其任务,所以它的括号中没有形参列表。
// This program has two functions: main and displayMessage.
#include <iostream>
using namespace std;
// Function prototype
void displayMessage();
//mian函数
int main()
{
cout << "Hello from main.\n";
displayMessage(); // Call.displayMessage
cout << "Now we are back in the main function again. \n";
return 0;
}
void displayMessage()
{
cout << "Hello from the displayMessage function.\n";
}
程序输出结果:
Hello from main.
Hello from the displayMessage function.
Now we are back in the main function again.
displayMessage();
请注意函数调用的形式,它只是函数的名称,后跟一组括号和分号。现在使用它来和函数头比较一下:请注意,函数调用不会包括返回类型。
可能有人会奇怪,上面程序中的第 6 行语句是做什么用的?它被称为函数原型,它的任务很简单,就是让编译器知道,在程序的后面将出现这个函数。它看起来很像是函数头,但它其实是一个语句,所以是以分号结束的。
#include <iostream>
using namespace std;
// Function prototype
void displayMessage();
int main()
{
cout << "Hello from main.\n";
for (int count = 0; count < 3; count++)
{
displayMessage() ; // Call displayMessage
}
cout << "Back in function main again.\n";
return 0;
}
void displayMessage()
{
cout << "Hello from the function displayMessage.\n";
}
程序输出结果:
Hello from main.
Hello from the displayMessage function.
Hello from the displayMessage function.
Hello from the displayMessage function.
Back in function main again.
#include <iostream>
using namespace std;
// Function prototype
void deep();
void deeper();
int main()
{
cout << "工 am starting in function main.\n";
deep(); // Call function deep
cout << "Now I amback in function main again.\n";
return 0;
}
void deep()
{
cout << "I am now inside the function deep.\n";
deeper(); // Call function deeper
cout << "Now I am back in deep. \n";
}
void deeper()
{
cout << "I am now inside the function deeper.\n";
}
程序输出结果:
I am starting in function main.
I am now inside the function deep.
I am now inside the function deeper.
Now I am back in deep.
Now I am back in function main again.
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有