c++第七天--特殊运算符的重载练习
1.定义复数类Complex,使得复数能够像实数一样用cin/cout输入和输出。(只能使用友元函数)
#include<iostream>
using namespace std;class Complex{
private:double real;double imag;
public:Complex(double real = 0,double imag = 0) : real(real),imag(imag) {}//友元函数重载输出运算符 << friend ostream& operator<<(ostream& out,const Complex&c){out << c.real;if(c.imag >= 0)out << " + " << c.imag << "i";elseout << c.imag << "i";}//友元函数重载输入运算符 >>friend istream& operator>>(istream& in,Complex& c){cout << "请输入实部与虚部: ";in >> c.real >> c.imag;return in;}
};int main()
{Complex c1;cin >> c1; //输入cout << "你输入的复数是:" << c1 << endl;return 0;
}
2.定义一个 MyString 类,包含一个字符指针 char* str 和一个整数 length,用于存储字符串和字符串的长度。确保在赋值过程中不会出现运行时错误。(重载=运算符)
//现在这个例子就是赋值运算符 (=)
//例子:定义一个Person类,包含char*类型的name和int age。
//在主函数中,定义两个Person对象p1和p2,把p1赋值给p2,输出两个对象的信息。
//现在这个方式就是运用赋值运算符
#include<iostream>
#include<string>
using namespace std;class Person
{
public:
//定义Person类Person(const char* name,int age) : age(age){int len = strlen(name);this -> name = new char[len+1];strcpy(this->name,name);}
//对其进行初始化Person() : name(0),age(0) {}
//释放内存,如果有名字的话,就对其进行去除~Person() {if(name) delete[] name;}
//友元函数friend ostream& operator<<(ostream& out,const Person& p){out << "name:" << p.name << "age:" << p.age << endl;return out;}
//赋值运算符Person& operator=(const Person& other){if(this != &other){if(name) delete[] name;int len = strlen(other.name);name = new char[len + 1];strcpy(name,other.name);age = other.age;}return *this;}
//拷贝构造函数
Person(const Person& other) :age(other.age){int len = strlen(other.name);name = new char[len + 1];strcpy(name,other.name);
}
private:char* name;int age;
};int main()
{Person p1("TOm",20);Person p2;p2 = p1; //赋值运算符重载Person p3 = p1; cout << p1 << endl;cout << p2 << endl;cout << p3 << endl;return 0;
}
- 定义一个 Time 类,用于表示时间,包含小时、分钟和秒。实现前置和后置自增 / 自减运算符重载,使得可以对时间对象进行自增 / 自减操作(秒数加 1 或减 1)。
#include <iostream>
using namespace std;class Time {
private:int hour, minute, second;void normalize() {if (second >= 60) {minute += second / 60;second %= 60;} else if (second < 0) {int borrow = (abs(second) + 59) / 60;minute -= borrow;second += borrow * 60;}if (minute >= 60) {hour += minute / 60;minute %= 60;} else if (minute < 0) {int borrow = (abs(minute) + 59) / 60;hour -= borrow;minute += borrow * 60;}if (hour < 0) hour = 0;}
public:Time(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {}// 前置自增Time& operator++() {++second;normalize();return *this;}// 后置自增Time operator++(int) {Time temp = *this;++second;normalize();return temp;}// 前置自减Time& operator--() {--second;normalize();return *this;}// 后置自减Time operator--(int) {Time temp = *this;--second;normalize();return temp;}void display() const {cout << hour << ":" << minute << ":" << second << endl;}
};int main() {Time t(1, 59, 59);++t;t.display(); // 2:0:0t++;t.display(); // 2:0:1--t;t.display(); // 2:0:0t--;t.display(); // 1:59:59return 0;
}