c++ 实现一个 结构体的 operator== 重载
时间: 2023-04-04 16:00:50 浏览: 124
可以实现一个结构体的 operator== 重载,需要在结构体内部定义一个 operator== 函数,该函数需要接受一个结构体类型的参数,并比较两个结构体的各个成员变量是否相等,最终返回一个布尔值表示是否相等。例如:
```
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
```
这样就可以使用 == 运算符比较两个 Person 结构体是否相等了。
相关问题
帮我用C++写一个结构体,包含+-*/重载运算符,拷贝函数,赋值函数,友元函数
好的,以下是一个示例:
```c++
#include <iostream>
using namespace std;
struct MyStruct {
int a, b;
MyStruct(int a = 0, int b = 0) : a(a), b(b) {}
// 加法运算符重载
MyStruct operator+(const MyStruct& other) const {
return MyStruct(a + other.a, b + other.b);
}
// 减法运算符重载
MyStruct operator-(const MyStruct& other) const {
return MyStruct(a - other.a, b - other.b);
}
// 乘法运算符重载
MyStruct operator*(const MyStruct& other) const {
return MyStruct(a * other.a, b * other.b);
}
// 除法运算符重载
MyStruct operator/(const MyStruct& other) const {
return MyStruct(a / other.a, b / other.b);
}
// 赋值函数
MyStruct& operator=(const MyStruct& other) {
a = other.a;
b = other.b;
return *this;
}
// 拷贝函数
MyStruct(const MyStruct& other) {
a = other.a;
b = other.b;
}
// 友元函数
friend ostream& operator<<(ostream& os, const MyStruct& obj) {
os << "a: " << obj.a << ", b: " << obj.b;
return os;
}
};
int main() {
MyStruct a(1, 2), b(3, 4), c;
// 测试加法运算符重载
c = a + b;
cout << "a + b = " << c << endl;
// 测试减法运算符重载
c = a - b;
cout << "a - b = " << c << endl;
// 测试乘法运算符重载
c = a * b;
cout << "a * b = " << c << endl;
// 测试除法运算符重载
c = a / b;
cout << "a / b = " << c << endl;
// 测试赋值函数
MyStruct d = a;
cout << "d = " << d << endl;
// 测试拷贝函数
MyStruct e(a);
cout << "e = " << e << endl;
return 0;
}
```
输出结果:
```
a + b = a: 4, b: 6
a - b = a: -2, b: -2
a * b = a: 3, b: 8
a / b = a: 0, b: 0
d = a: 1, b: 2
e = a: 1, b: 2
```
结构体重载等于号
在C++中,结构体可以通过重载运算符实现自定义的操作。重载等于号运算符(operator=)是其中之一。
下面是一个简单的结构体示例,其中包含了一个字符串成员:
```c++
struct Person {
std::string name;
};
```
为了支持结构体的赋值操作,我们可以重载等于号运算符,实现自定义的逻辑。这里是一个重载等于号运算符的示例:
```c++
struct Person {
std::string name;
// 重载等于号运算符
Person& operator=(const Person& other) {
if (this != &other) { // 避免自我赋值
name = other.name;
}
return *this;
}
};
```
在这个示例中,重载等于号运算符返回一个指向自身的引用,这样可以支持连续赋值操作。在函数内部,我们使用了传递进来的另一个对象的成员变量值来更新当前对象的成员变量。
使用重载等于号运算符的示例:
```c++
Person p1;
p1.name = "Alice";
Person p2;
p2.name = "Bob";
p2 = p1; // 调用重载的等于号运算符
std::cout << p2.name << std::endl; // 输出 "Alice"
```
在上面的示例中,我们调用了重载的等于号运算符,将p1的值赋给了p2。最后输出p2的name成员变量值,可以看到它已经被更新为"Alice"。