C++中立方运算,用到重载与输出流
时间: 2024-05-07 13:20:31 浏览: 97
可以通过重载运算符和输出流来实现C++中立方运算。下面是一段示例代码:
```c++
#include <iostream>
using namespace std;
class Cube {
public:
double length;
Cube() {
length = 0;
}
Cube(double len) {
length = len;
}
Cube operator+(const Cube& c) {
Cube cube;
cube.length = this->length + c.length;
return cube;
}
Cube operator-(const Cube& c) {
Cube cube;
cube.length = this->length - c.length;
return cube;
}
Cube operator*(const Cube& c) {
Cube cube;
cube.length = this->length * c.length;
return cube;
}
Cube operator/(const Cube& c) {
Cube cube;
cube.length = this->length / c.length;
return cube;
}
Cube operator^(const int n) {
Cube cube;
cube.length = pow(this->length, n);
return cube;
}
friend ostream& operator<<(ostream& os, const Cube& c) {
os << "Length: " << c.length << endl;
return os;
}
};
int main() {
Cube c1(3);
Cube c2(2);
Cube c3 = c1 + c2;
cout << c3;
Cube c4 = c1 - c2;
cout << c4;
Cube c5 = c1 * c2;
cout << c5;
Cube c6 = c1 / c2;
cout << c6;
Cube c7 = c1 ^ 3;
cout << c7;
return 0;
}
```
在这个示例中,Cube类表示一个立方体,其中重载了加、减、乘、除、幂运算符,以实现立方运算。此外,还重载了输出流运算符,以便在输出时可以直接打印对象的属性。在主函数中,创建了两个Cube对象,然后进行了各种运算,并将结果输出到控制台。
阅读全文