以下代码使用了 cin 且展示了 cout 的多功能性:

  1. #include <iostream>
  2. int main()
  3. {
  4. using namespace std;
  5. int carrots;
  6. cout << "How manny carrots do you have?" << endl;
  7. cin >> carrots;
  8. cout << "Now you have " << carrots << " carrots." << endl;
  9. return 0;
  10. }

2.3.1 使用 cin

上述代码中,信息从 cin 流向 carrots。iostream 文件将 cin 定义为一个表示输出流的对象。

2.3.2 使用 count 拼接

使用 count 可以将4条输出语句合并为一条,以下代码相同:

  1. //第一种
  2. count << "Now you have " << carrots << " carrots." << endl;
  3. //第二种
  4. count << "Now you have ";
  5. count << carrots;
  6. count << " carrots.";
  7. count << endl;
  8. //第三种
  9. count << "Now you have "
  10. << carrots
  11. << " carrots."
  12. << endl;

2.3.3 类简介

类是 C++ 中面向对象编程(OOP)的核心概念之一。类是用户定义的一种数据类型,描述了“表示什么信息”、“可以对数据执行哪些操作”。