C++ >> 和<<使用实例
时间: 2023-08-17 15:55:50 浏览: 52
当我们在C++中使用`>>`和`<<`运符时,通常及到输入和输出流。这些运算用于输入和输出数据到流中。
下面是一些关于`>>`和`<<`的使用示例:
1. 输出数据到控制台:
```cpp
#include <iostream>
int main() {
int num = 10;
std::cout << "The number is: " << num << std::endl;
return 0;
}
```
输出:
```
The number is: 10
```
2. 从用户输入读取数据:
```cpp
#include <iostream>
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << "You entered: " << num << std::endl;
return 0;
}
```
输入:
```
Enter a number: 20
```
输出:
```
You entered: 20
```
3. 自定义输出运算符重载:
```cpp
#include <iostream>
class Point {
private:
int x, y;
public:
Point(int x, int y) : x(x), y(y) {}
friend std::ostream& operator<<(std::ostream& os, const Point& p) {
os << "Point(" << p.x << ", " << p.y << ")";
return os;
}
};
int main() {
Point p(3, 5);
std::cout << "The point is: " << p << std::endl;
return 0;
}
```
输出:
```
The point is: Point(3, 5)
```
4. 自定义输入运算符重载:
```cpp
#include <iostream>
class Point {
private:
int x, y;
public:
Point() {}
friend std::istream& operator>>(std::istream& is, Point& p) {
std::cout << "Enter x and y coordinates: ";
is >> p.x >> p.y;
return is;
}
friend std::ostream& operator<<(std::ostream& os, const Point& p) {
os << "Point(" << p.x << ", " << p.y << ")";
return os;
}
};
int main() {
Point p;
std::cin >> p;
std::cout << "The point is: " << p << std::endl;
return 0;
}
```
输入:
```
Enter x and y coordinates: 3 5
```
输出:
```
The point is: Point(3, 5)
```
这些是一些常见的`>>`和`<<`运算符的使用示例。在C++中,我们可以通过重载这些运算符来自定义输入和输出操作,以适应我们的自定义类型。