帮我用c++写一个类 包含+ - / * == > <重载运算符,友元函数,以及使用,写出完整代码
时间: 2024-02-16 07:00:37 浏览: 68
C++运算符重载 成员函数与友元函数详解
5星 · 资源好评率100%
好的,以下是一个简单的C++类,包含重载+、-、*、/、==、>、<运算符,以及友元函数。同时,还提供了一个使用该类的示例。
```c++
#include <iostream>
class MyClass {
public:
MyClass(int a = 0, int b = 0) : x(a), y(b) {}
MyClass operator+(const MyClass& other) const {
return MyClass(x + other.x, y + other.y);
}
MyClass operator-(const MyClass& other) const {
return MyClass(x - other.x, y - other.y);
}
MyClass operator*(const MyClass& other) const {
return MyClass(x * other.x, y * other.y);
}
MyClass operator/(const MyClass& other) const {
return MyClass(x / other.x, y / other.y);
}
bool operator==(const MyClass& other) const {
return (x == other.x) && (y == other.y);
}
bool operator>(const MyClass& other) const {
return (x > other.x) && (y > other.y);
}
bool operator<(const MyClass& other) const {
return (x < other.x) && (y < other.y);
}
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj);
private:
int x;
int y;
};
std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "(" << obj.x << ", " << obj.y << ")";
return os;
}
int main() {
MyClass a(1, 2);
MyClass b(3, 4);
MyClass c = a + b;
MyClass d = a - b;
MyClass e = a * b;
MyClass f = a / b;
std::cout << "a = " << a << ", b = " << b << std::endl;
std::cout << "a + b = " << c << std::endl;
std::cout << "a - b = " << d << std::endl;
std::cout << "a * b = " << e << std::endl;
std::cout << "a / b = " << f << std::endl;
std::cout << "a == b? " << (a == b) << std::endl;
std::cout << "a > b? " << (a > b) << std::endl;
std::cout << "a < b? " << (a < b) << std::endl;
return 0;
}
```
输出结果为:
```
a = (1, 2), b = (3, 4)
a + b = (4, 6)
a - b = (-2, -2)
a * b = (3, 8)
a / b = (0, 0)
a == b? 0
a > b? 0
a < b? 1
```
阅读全文