3.1 创建函数
标准C和C++有一个特诊叫做函数原型。用函数原型,在声明和定义一个函数时,必须使用参数类型描述。
注意:对于没有参数的函数。如
function()
在C中,它意味着不确定参数数目;而在C++中,表示没有参数的函数。
3.1.1 函数的返回值
C++函数原型必须指明函数的返回值类型(在C中,如果省略返回值,表示默认为整型),返回值类型放在函数名的前面。如果表明没有返回值类型可以使用void关键字。
要从一个函数得到返回值,必须使用return语句。例:return的运用:
//:C02:Return.cpp
// Use of "return"
#include <iostream>
using namespace std;
char cfunc(int i)
{
if (0 == i)
{
return 0;
}
if (1 == i)
{
return 'g';
}
if (5 == i)
{
return 'z';
}
else{
return 'c';
}
}
int main()
{
cout << "type an integer: ";
int val;
cin >> val;
cout << cfunc(val) << endl;
} ///:~
3.1.2 使用C的函数库
使用库函数的方法如下:在编程参考资料中查找函数。函数的描述应该包括说明代码语法的部分。这部分的头部通常至少有一个#include行,表示包含函数原型的头文件。
3.1.3 通过库管理器创建自己的库
如果想创建一个库,那么就建立一个头文件,它包含库中的所有函数原型。把这个头文件放置在预处理器搜索路径中的某处,或者当前目录中,或者在包含路径中。
3.2 执行控制语句
C++使用C的所有执行控制语句。这些语句包括if-else\while\do-while\for和switch选择语句。
3.2.1 真和假
A == B 是一个条件表达式,其中“==”意思是相等,通过“==”确定A是否与B相等。表达式产生布尔值true或false。其他条件运算符有:>、<、>=等
3.2.2 if-else语句
if-else语句有两种形式:用else或不用else。这两种形式是:
if (表达式)
语句
或
if (表达式)
语句
else
语句
表达式的值为真或假。例:
//:C02:Ifthen.cpp
// Demonstration of if and if-else conditionals
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "type a number and 'Enter'" << endl;
cin >> i;
if (i >5)
{
cout << "It's greater than 5" << endl;
}
else
{
if (i < 5)
{
cout << "It's less than 5 " << endl;
}
else
{
cout << "It's equal to 5 " << endl;
}
}
cout << "type a number and 'Enter'" << endl;
cin >> i;
if (i < 10)
{
if (i > 5)
{
cout << "5 < i < 10" << endl;
}
else
{
cout << "i <= 5" << endl;
}
}
else
{
cout << "i >= 10" << endl;
}
}
在使用if-else时,注意配套,最好每个都用{}显示不同的if-else。
3.2.3 while语句
while、do-while和for语句是循环控制语句。
while循环的形式是:
while (表达式)
语句
循环一开始就对表达式进行计算。并在每次重复执行语句之前再次计算。
//:C02:Guess.cpp
// Guess a number
#include <iostream>
using namespace std;
int main()
{
int secret = 15;
int guess = 0;
while (guess != secret)
{
cout << "Guess the number: ";
cin >> guess;
}
cout << "You guessed it!" << endl;
} ///:~
3.2.4 do-while语句
do-while的形式是:
do
语句
while (表达式)
do-while语句与while语句的区别在于:即使表达式第一次计值就等于假,前面的语句也会至少执行一次。在一般的while语句中,如果条件第一次为假,语句一次也不会执行。例:
//:C02:Guess2.cpp
// The guess program using do-while
#include <iostream>
using namespace std;
int main()
{
int secret = 15;
int guess;
do
{
cout << "guess the number: ";
cin >> guess;
}
while (guess != secret);
cout << "You got it!" << endl;
} ///:~
注意while后面还有一个分号。
3.2.5 for语句
for循环的形式是:
for (initialization; conditional; step)
语句
表达式中的initialization、conditional或step都可能为空。
for循环通常用语“计数”任务。例:
//:C02:Charlist.cpp
// Display all the ASCII characters
// Demonstrates "for"
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 128; i = i + 1)
{
if (26 !=i)
{
cout << "value: " << i
<< " character: "
<< char(i)
<< endl;
}
}
} ///:~