cpp实现运算符重载+-负号重载通过对象进行输出运算后结果
下面是一个示例代码,演示了如何在C++中实现运算符重载+、-(负号),以及重载<<、>>运算符。
#include<iostream>
using namespace std;
class MyNumber {
private:
int value;
public:
MyNumber(int val) {
value = val;
}
// 重载+运算符
MyNumber operator+(const MyNumber& other) const {
return MyNumber(value + other.value);
}
// 重载-(负号)运算符
MyNumber operator-() const {
return MyNumber(-value);
}
// 重载<<运算符
friend ostream& operator<<(ostream& os, const MyNumber& obj) {
os << obj.value;
return os;
}
// 重载>>运算符
friend istream& operator>>(istream& is, MyNumber& obj) {
is >> obj.value;
return is;
}
};
int main() {
MyNumber num1(10);
MyNumber num2(5);
// 使用重载的+运算符
MyNumber sum = num1 + num2;
cout << "Sum: " << sum << endl;
// 使用重载的-(负号)运算符
MyNumber neg = -num1;
cout << "Negation: " << neg << endl;
// 使用重载的>>运算符
cout << "Enter a number: ";
cin >> num1;
// 使用重载的<<运算符
cout << "Number entered: " << num1 << endl;
return 0;
}
运行上述代码,输出结果如下:
Sum: 15
Negation: -10
Enter a number: 20
Number entered: 20
在上述代码中,MyNumber类重载了+运算符,使得两个MyNumber对象可以相加。重载-(负号)运算符,使得一个MyNumber对象可以取负。重载<<运算符,使得可以通过对象进行输出运算。重载>>运算符,使得可以通过对象进行输入运算。
原文地址: https://www.cveoy.top/t/topic/i9Xe 著作权归作者所有。请勿转载和采集!