以下代码使用了 cin 且展示了 cout 的多功能性:
#include <iostream>
int main()
{
using namespace std;
int carrots;
cout << "How manny carrots do you have?" << endl;
cin >> carrots;
cout << "Now you have " << carrots << " carrots." << endl;
return 0;
}
2.3.1 使用 cin
上述代码中,信息从 cin 流向 carrots。iostream 文件将 cin 定义为一个表示输出流的对象。
2.3.2 使用 count 拼接
使用 count 可以将4条输出语句合并为一条,以下代码相同:
//第一种
count << "Now you have " << carrots << " carrots." << endl;
//第二种
count << "Now you have ";
count << carrots;
count << " carrots.";
count << endl;
//第三种
count << "Now you have "
<< carrots
<< " carrots."
<< endl;
2.3.3 类简介
类是 C++ 中面向对象编程(OOP)的核心概念之一。类是用户定义的一种数据类型,描述了“表示什么信息”、“可以对数据执行哪些操作”。