阅读量:2
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;
}
这些示例展示了如何为自定义类型重载运算符,以便我们可以像使用内置类型一样使用它们。请注意,当重载运算符时,我们需要遵循一些规则,例如保持运算符的语义一致,并确保重载的运算符具有合适的行为。
以上就是关于“c++operator如何运用”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm