C++20个运算符重载类上机示例
·
1. 基本算术运算符重载
#include <iostream>
using namespace std;
class Complex {
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载+运算符
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 重载-运算符
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
void display() const {
cout << real << (imag >= 0 ? "+" : "") << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4), c2(1, -2);
Complex sum = c1 + c2;
Complex diff = c1 - c2;
cout << "Sum: "; sum.display();
cout << "Difference: "; diff.display();
return 0;
}
2. 关系运算符重载
#include <iostream>
using namespace std;
class Date {
int day, month, year;
public:
Date(int d, int m, int y) : day(d), month(m), year(y) {}
// 重载==运算符
bool operator==(const Date& other) const {
return day == other.day && month == other.month && year == other.year;
}
// 重载<运算符
bool operator<(const Date& other) const {
if (year != other.year) return year < other.year;
if (month != other.month) return month < other.month;
return day < other.day;
}
void display() const {
cout << day << "/" << month << "/" << year << endl;
}
};
int main() {
Date d1(15, 6, 2023), d2(20, 6, 2023);
cout << "d1 == d2: " << (d1 == d2) << endl;
cout << "d1 < d2: " << (d1 < d2) << endl;
return 0;
}
3. 流插入和提取运算符重载
#include <iostream>
using namespace std;
class Student {
string name;
int age;
public:
Student(const string& n = "", int a = 0) : name(n), age(a) {}
// 重载<<运算符
friend ostream& operator<<(ostream& os, const Student& s) {
os << "Name: " << s.name << ", Age: " << s.age;
return os;
}
// 重载>>运算符
friend istream& operator>>(istream& is, Student& s) {
cout << "Enter name: ";
is >> s.name;
cout << "Enter age: ";
is >> s.age;
return is;
}
};
int main() {
Student s;
cin >> s;
cout << s << endl;
return 0;
}
4. 下标运算符重载
#include <iostream>
#include <stdexcept>
using namespace std;
class IntArray {
int* arr;
int size;
public:
IntArray(int s) : size(s) {
arr = new int[size];
}
~IntArray() {
delete[] arr;
}
// 重载[]运算符
int& operatorint index {
if (index < 0 || index >= size) {
throw out_of_range("Index out of range");
}
return arr[index];
}
// const版本的重载
const int& operatorint index const {
if (index < 0 || index >= size) {
throw out_of_range("Index out of range");
}
return arr[index];
}
};
int main() {
IntArray arr(5);
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
5. 赋值运算符重载
#include <iostream>
using namespace std;
class String {
char* str;
int length;
public:
String(const char* s = "") {
length = strlen(s);
str = new char[length + 1];
strcpy(str, s);
}
~String() {
delete[] str;
}
// 重载=运算符
String& operator=(const String& other) {
if (this != &other) {
delete[] str;
length = other.length;
str = new char[length + 1];
strcpy(str, other.str);
}
return *this;
}
void display() const {
cout << str << endl;
}
};
int main() {
String s1("Hello"), s2("World");
s1 = s2;
s1.display();
return 0;
}
6. 函数调用运算符重载
#include <iostream>
using namespace std;
class Multiplier {
int factor;
public:
Multiplier(int f) : factor(f) {}
// 重载()运算符
int operator()(int x) const {
return x * factor;
}
};
int main() {
Multiplier times5(5);
cout << "7 multiplied by 5 is " << times5(7) << endl;
return 0;
}
7. 递增递减运算符重载
#include <iostream>
using namespace std;
class Counter {
int count;
public:
Counter(int c = 0) : count(c) {}
// 前置++
Counter& operator++() {
++count;
return *this;
}
// 后置++
Counter operator++(int) {
Counter temp = *this;
++count;
return temp;
}
// 前置--
Counter& operator--() {
--count;
return *this;
}
// 后置--
Counter operator--(int) {
Counter temp = *this;
--count;
return temp;
}
int getCount() const { return count; }
};
int main() {
Counter c(5);
cout << "Original: " << c.getCount() << endl;
++c;
cout << "After prefix ++: " << c.getCount() << endl;
c++;
cout << "After postfix ++: " << c.getCount() << endl;
--c;
cout << "After prefix --: " << c.getCount() << endl;
c--;
cout << "After postfix --: " << c.getCount() << endl;
return 0;
}
8. 类型转换运算符重载
#include <iostream>
using namespace std;
class Fahrenheit {
double temp;
public:
Fahrenheit(double t) : temp(t) {}
// 重载double类型转换运算符
operator double() const {
return (temp - 32) * 5 / 9;
}
double getTemp() const { return temp; }
};
int main() {
Fahrenheit f(212);
double celsius = f; // 隐式转换
cout << f.getTemp() << "°F = " << celsius << "°C" << endl;
return 0;
}
9. 成员访问运算符重载
#include <iostream>
using namespace std;
class SmartPointer {
int* ptr;
public:
SmartPointer(int* p = nullptr) : ptr(p) {}
~SmartPointer() { delete ptr; }
// 重载*运算符
int& operator*() { return *ptr; }
// 重载->运算符
int* operator->() { return ptr; }
};
int main() {
SmartPointer sp(new int(42));
cout << "Value: " << *sp << endl;
*sp = 100;
cout << "New value: " << *sp << endl;
return 0;
}
10. 逻辑运算符重载
#include <iostream>
using namespace std;
class Boolean {
bool value;
public:
Boolean(bool v = false) : value(v) {}
// 重载!运算符
bool operator!() const {
return !value;
}
// 重载&&运算符
bool operator&&(const Boolean& other) const {
return value && other.value;
}
// 重载||运算符
bool operator||(const Boolean& other) const {
return value || other.value;
}
bool getValue() const { return value; }
};
int main() {
Boolean b1(true), b2(false);
cout << "!b1: " << !b1 << endl;
cout << "b1 && b2: " << (b1 && b2) << endl;
cout << "b1 || b2: " << (b1 || b2) << endl;
return 0;
}
11. 位运算符重载
#include <iostream>
using namespace std;
class BitMask {
unsigned int mask;
public:
BitMask(unsigned int m = 0) : mask(m) {}
// 重载&运算符
BitMask operator&(const BitMask& other) const {
return BitMask(mask & other.mask);
}
// 重载|运算符
BitMask operator|(const BitMask& other) const {
return BitMask(mask | other.mask);
}
// 重载^运算符
BitMask operator^(const BitMask& other) const {
return BitMask(mask ^ other.mask);
}
// 重载~运算符
BitMask operator~() const {
return BitMask(~mask);
}
// 重载<<运算符
BitMask operator<<(int shift) const {
return BitMask(mask << shift);
}
// 重载>>运算符
BitMask operator>>(int shift) const {
return BitMask(mask >> shift);
}
unsigned int getMask() const { return mask; }
};
int main() {
BitMask b1(0b1010), b2(0b1100);
cout << "b1 & b2: " << (b1 & b2).getMask() << endl;
cout << "b1 | b2: " << (b1 | b2).getMask() << endl;
cout << "b1 ^ b2: " << (b1 ^ b2).getMask() << endl;
cout << "~b1: " << (~b1).getMask() << endl;
cout << "b1 << 1: " << (b1 << 1).getMask() << endl;
cout << "b2 >> 1: " << (b2 >> 1).getMask() << endl;
return 0;
}
12. 复合赋值运算符重载
#include <iostream>
using namespace std;
class Account {
double balance;
public:
Account(double b = 0) : balance(b) {}
// 重载+=运算符
Account& operator+=(double amount) {
balance += amount;
return *this;
}
// 重载-=运算符
Account& operator-=(double amount) {
balance -= amount;
return *this;
}
// 重载*=运算符
Account& operator*=(double rate) {
balance *= rate;
return *this;
}
double getBalance() const { return balance; }
};
int main() {
Account acc(1000);
acc += 500;
cout << "After deposit: " << acc.getBalance() << endl;
acc -= 200;
cout << "After withdrawal: " << acc.getBalance() << endl;
acc *= 1.05;
cout << "After interest: " << acc.getBalance() << endl;
return 0;
}
13. 比较运算符全重载
#include <iostream>
using namespace std;
class Temperature {
double celsius;
public:
Temperature(double c = 0) : celsius(c) {}
// 重载==运算符
bool operator==(const Temperature& other) const {
return celsius == other.celsius;
}
// 重载!=运算符
bool operator!=(const Temperature& other) const {
return !(*this == other);
}
// 重载<运算符
bool operator<(const Temperature& other) const {
return celsius < other.celsius;
}
// 重载>运算符
bool operator>(const Temperature& other) const {
return celsius > other.celsius;
}
// 重载<=运算符
bool operator<=(const Temperature& other) const {
return celsius <= other.celsius;
}
// 重载>=运算符
bool operator>=(const Temperature& other) const {
return celsius >= other.celsius;
}
double getCelsius() const { return celsius; }
};
int main() {
Temperature t1(25), t2(30);
cout << "t1 == t2: " << (t1 == t2) << endl;
cout << "t1 != t2: " << (t1 != t2) << endl;
cout << "t1 < t2: " << (t1 < t2) << endl;
cout << "t1 > t2: " << (t1 > t2) << endl;
cout << "t1 <= t2: " << (t1 <= t2) << endl;
cout << "t1 >= t2: " << (t1 >= t2) << endl;
return 0;
}
14. 逗号运算符重载
#include <iostream>
using namespace std;
class Point {
int x, y;
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
// 重载,运算符
Point operator,(const Point& other) const {
return other; // 通常返回最后一个操作数
}
void display() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(1, 2), p2(3, 4), p3(5, 6);
Point result = (p1, p2, p3); // 返回最后一个操作数p3
result.display();
return 0;
}
15. 指针运算符重载
#include <iostream>
using namespace std;
class SafePointer {
int* ptr;
public:
SafePointer(int* p = nullptr) : ptr(p) {}
~SafePointer() { delete ptr; }
// 重载*运算符
int& operator*() {
if (ptr == nullptr) {
throw runtime_error("Dereferencing null pointer");
}
return *ptr;
}
// 重载->运算符
int* operator->() {
if (ptr == nullptr) {
throw runtime_error("Accessing null pointer");
}
return ptr;
}
// 重载bool转换运算符
explicit operator bool() const {
return ptr != nullptr;
}
};
int main() {
SafePointer sp(new int(42));
if (sp) {
cout << "Value: " << *sp << endl;
*sp = 100;
cout << "New value: " << *sp << endl;
}
return 0;
}
16. 数组运算符重载
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
vector<vector<int>> data;
public:
Matrix(int rows, int cols) : data(rows, vector<int>(cols)) {}
// 重载[]运算符
vector<int>& operatorint row {
return data[row];
}
// const版本的重载
const vector<int>& operatorint row const {
return data[row];
}
int rows() const { return data.size(); }
int cols() const { return data.empty() ? 0 : data[0].size(); }
};
int main() {
Matrix mat(3, 3);
for (int i = 0; i < mat.rows(); i++) {
for (int j = 0; j < mat.cols(); j++) {
mat[i][j] = i * mat.cols() + j;
}
}
for (int i = 0; i < mat.rows(); i++) {
for (int j = 0; j < mat.cols(); j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
return 0;
}
17. 算术运算符全局重载
#include <iostream>
using namespace std;
class Fraction {
int numerator, denominator;
public:
Fraction(int n = 0, int d = 1) : numerator(n), denominator(d) {}
void simplify() {
int gcd = findGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
int findGCD(int a, int b) {
return b == 0 ? a : findGCD(b, a % b);
}
friend Fraction operator+(const Fraction& f1, const Fraction& f2);
friend Fraction operator*(const Fraction& f1, const Fraction& f2);
void display() const {
cout << numerator << "/" << denominator << endl;
}
};
// 全局重载+运算符
Fraction operator+(const Fraction& f1, const Fraction& f2) {
Fraction result(f1.numerator * f2.denominator + f2.numerator * f1.denominator,
f1.denominator * f2.denominator);
result.simplify();
return result;
}
// 全局重载*运算符
Fraction operator*(const Fraction& f1, const Fraction& f2) {
Fraction result(f1.numerator * f2.numerator,
f1.denominator * f2.denominator);
result.simplify();
return result;
}
int main() {
Fraction f1(1, 2), f2(1, 3);
Fraction sum = f1 + f2;
Fraction product = f1 * f2;
cout << "Sum: "; sum.display();
cout << "Product: "; product.display();
return 0;
}
18. 自定义内存分配运算符重载
#include <iostream>
#include <cstdlib>
using namespace std;
class MemoryDemo {
int* ptr;
public:
MemoryDemo() : ptr(nullptr) {}
// 重载new运算符
void* operator new(size_t size) {
cout << "Custom new for size: " << size << endl;
return malloc(size);
}
// 重载delete运算符
void operator delete(void* p) {
cout << "Custom delete" << endl;
free(p);
}
// 重载new[]运算符
void* operator newsize_t size {
cout << "Custom new[] for size: " << size << endl;
return malloc(size);
}
// 重载delete[]运算符
void operator deletevoid* p {
cout << "Custom delete[]" << endl;
free(p);
}
};
int main() {
MemoryDemo* obj = new MemoryDemo;
delete obj;
MemoryDemo* arr = new MemoryDemo[5];
delete[] arr;
return 0;
}
19. 用户定义字面量运算符重载
#include <iostream>
using namespace std;
class Distance {
double meters;
public:
Distance(double m = 0) : meters(m) {}
// 重载用户定义字面量运算符
friend Distance operator"" _km(long double km) {
return Distance(km * 1000);
}
friend Distance operator"" _m(long double m) {
return Distance(m);
}
friend Distance operator"" _cm(long double cm) {
return Distance(cm / 100);
}
double getMeters() const { return meters; }
};
int main() {
Distance d1 = 1.5_km;
Distance d2 = 500_m;
Distance d3 = 75_cm;
cout << "1.5 km = " << d1.getMeters() << " m" << endl;
cout << "500 m = " << d2.getMeters() << " m" << endl;
cout << "75 cm = " << d3.getMeters() << " m" << endl;
return 0;
}
20. 三路比较运算符重载(C++20)
#include <iostream>
#include <compare>
using namespace std;
class Version {
int major, minor, patch;
public:
Version(int ma = 0, int mi = 0, int pa = 0)
: major(ma), minor(mi), patch(pa) {}
// 重载<=>运算符(C++20)
auto operator<=>(const Version& other) const = default;
void display() const {
cout << major << "." << minor << "." << patch << endl;
}
};
int main() {
Version v1(1, 2, 3), v2(1, 2, 4);
if (v1 < v2) cout << "v1 is less than v2" << endl;
if (v1 <= v2) cout << "v1 is less than or equal to v2" << endl;
if (v1 > v2) cout << "v1 is greater than v2" << endl;
if (v1 >= v2) cout << "v1 is greater than or equal to v2" << endl;
if (v1 == v2) cout << "v1 is equal to v2" << endl;
if (v1 != v2) cout << "v1 is not equal to v2" << endl;
return 0;
}
更多推荐
所有评论(0)