C++中的运算符(operator)是一种特殊的函数,它允许我们在代码中以简洁的方式执行常见的操作。运算符重载是C++中的一个重要特性,它允许我们为自定义类型(如类或结构体)定义运算符的行为。
以下是一些常见的运算符及其用法:
class MyNumber { public: int value; MyNumber(int v) : value(v) {} MyNumber operator+(const MyNumber& other) const { return MyNumber(value + other.value); } }; int main() { MyNumber a(3); MyNumber b(4); MyNumber c = a + b; // 使用重载的运算符 return 0; } class MyString { public: std::string str; MyString(const std::string& s) : str(s) {} bool operator==(const MyString& other) const { return str == other.str; } }; int main() { MyString s1("hello"); MyString s2("world"); MyString s3 = s1; if (s1 == s2) { // 使用重载的运算符 std::cout << "s1 and s2 are equal" << std::endl; } else { std::cout << "s1 and s2 are not equal" << std::endl; } if (s1 == s3) { // 使用重载的运算符 std::cout << "s1 and s3 are equal" << std::endl; } else { std::cout << "s1 and s3 are not equal" << std::endl; } return 0; } class MyArray { public: int* data; int size; MyArray(int* d, int s) : data(d), size(s) {} MyArray& operator=(const MyArray& other) { if (this != &other) { delete[] data; data = new int[other.size]; size = other.size; std::copy(other.data, other.data + size, data); } return *this; } }; int main() { int arr[] = {1, 2, 3, 4, 5}; MyArray a(arr, 5); MyArray b = a; // 使用重载的运算符 return 0; } class MyBool { public: bool value; MyBool(bool v) : value(v) {} MyBool operator!(const MyBool& other) const { return MyBool(!other.value); } }; int main() { MyBool a(true); MyBool b = !a; // 使用重载的运算符 return 0; } 这些示例展示了如何为自定义类型重载运算符,以便我们可以像使用内置类型一样使用它们。请注意,当重载运算符时,我们需要遵循一些规则,例如保持运算符的语义一致,并确保重载的运算符具有合适的行为。