哪位高手知道C++中结构体类型的数据怎么运算啊?

来源:百度知道 编辑:UC知道 时间:2024/05/10 07:45:06
题目是这样的定义结构体类型triangle,表示一个矩形,他的两个数据成员length和width分别表示长和宽,定义函数完成其类型数据的相加,其中length与width分别相加…
等待高手中…
第一个回答编译通过,可有点就是如果要增加读取这个triangle的数据再进行相加该咋办啊

#include <iostream>
using namespace std;
struct triangle
{
int length;
int width;
triangle(int a=0, int b=0)
{length=a;width=b;};
triangle operator +(triangle& other)
{
triangle result;
result.length=this->length+other.length;
result.width=this->width+other.width;
return result;
}
};

int main()
{
triangle a(1,2),b(3,4),c;
c=a+b;
cout<<c.length<<endl;
cout<<c.width<<endl;
return 0;
}

把前面回答的回答的triangle a(1,2),b(3,4),c; 改成

int length1,length2,width1,width2;
cout<<"请输入第一个矩形的长和宽"<<endl;
cin>>length1>>width1;
cout<<"请输入第二个矩形的长和宽"<<endl;
cin>>length2>>width2;
triangle a(length1,width1),b(length2,width2),c;
就可以了!呵呵