声明一个类Triangle,其中包括三角形的三条边,三条边的默认值 为3、4、5,另外也支持在建立对象时初始化其他的值; 2.定义两个对象t1t2,其中t/1的三条边取默认值,t2的三条边初 始化为6.8.10; 3. 再定义一个对象计3,要求通过运算符重载实现 tr3=tr1 +tr2,并输 出tr3的当据
时间: 2024-03-12 22:50:13 浏览: 26
好的,以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Triangle {
private:
double a, b, c; // 三角形的三条边
public:
// 构造函数,默认值为3、4、5
Triangle(double _a = 3, double _b = 4, double _c = 5) : a(_a), b(_b), c(_c) {}
// 拷贝构造函数
Triangle(const Triangle& t) : a(t.a), b(t.b), c(t.c) {}
// 运算符重载:加法
Triangle operator+(const Triangle& t) const {
return Triangle(a + t.a, b + t.b, c + t.c);
}
// 输出三角形的三条边
void show() {
cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
}
};
int main() {
Triangle t1; // 默认值为3、4、5
Triangle t2(6, 8, 10); // 值为6、8、10
Triangle t3 = t1 + t2; // 重载加法运算符
t3.show(); // 输出t3的三条边
return 0;
}
```
输出结果为:
```
a = 9, b = 12, c = 15
```
说明运算符重载成功,t3的三条边是t1和t2三条边对应相加的结果。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)