第二章 开始学习C++
2.1进入C++
// myfirst.cpp--displays a message
#include <iostream> // a PREPROCESSOR directive
int main() // function header
{ // start of function body
using namespace std; // make definitions visible
cout << "Come up and C++ me some time."; // message
cout << endl; // start a new line
cout << "You won't regret it!" << endl; // more output
// If the output window closes before you can read it,
// add the following code:
// cout << "Press any key to continue." <<endl;
// cin.get();
return 0; // terminate main()
} // end of function body
利用myfirst来初识C++的基本架构:
注释,由前缀 // 标识
预处理器编译指令 #include
编译指令 using namespace
函数体,用 {} 括起
使用C++的cout工具显示消息的语句
结束main()函数的return语句
2.1.1 main()函数
作为接口的函数头
C++程序必须包含一个名为main()的函数。
2.1.2 C++注释
C++注释以 // 打头,到行尾结束。
2.1.3 C++预处理器和iostream文件
程序要使用C++输入或输出工具,须有以下两行代码:
#include
using namespace std;
注意:使用cin和cout必须包含文件iostream
2.1.6 使用cout进行C++输出
控制符 endl
cout<<endl;
表示概念:重起一行
换行符 \n
2.2 C++语句
// carrots.cpp -- food processing program
// uses and displays a variable
#include <iostream>
int main()
{
using namespace std;
int carrots; // declare an integer variable
carrots = 25; // assign a value to the variable
cout << "I have ";
cout << carrots; // display the value of the variable
cout << " carrots.";
cout << endl;
carrots = carrots - 1; // modify the variable
cout << "Crunch, crunch. Now I have " << carrots << " carrots." << endl;
// cin.get();
return 0;
}
从上述carrot.cpp来看C++语句
2.2.1 声明语句和变量
变量必须声明
对于声明变量,C++的做法是尽可能在首次使用变量前声明它
2.2.2 赋值语句
赋值语句将值赋给存储单元
符号=叫做赋值运算符