c++ - 友元函数运算符重载参数表中如何写多个参数一起进行操作
本文介绍了c++ - 友元函数运算符重载参数表中如何写多个参数一起进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
这是一个三角类Triangle,重载运算符+来实现两个三角形对象的面积之和
如何改进成计算任意多个三角形的面积之和?
我这样重载+符合实现对两个三角形对象的面积之和吗?
#include <iostream>
#include <math.h>
using namespace std;
class Triangle
{
private:
int x,y,z;
public:
Triangle(){}
void area()
{
float s,area;
s=(x+y+z)/2;
area=sqrt(s*(s-x)*(s-y)*(s-z));
cout<<"area is "<<area<<endl;
}
friend Triangle operator+(Triangle b1,Triangle b2)
{
Triangle b;
b.x=b1.x+b2.x;
b.y=b1.y+b2.y;
b.z=b1.z+b2.z;
return b;
}
void input()
{
cin>>x>>y>>z;
}
void output()
{
cout<<"triangle three horizon length is "<<x<<" "<<y<<" "<<z<<endl;
}
};
int main()
{
Triangle a,b;
a.input();
b.input();
(a+b).output();
(a+b).area();
return 0;
}
解决方案
一般不会(a + b).area(); 这样调用,用起来不自然。
而是会实现类似下面的一个重载函数
friend ostream &operator<<(ostream &os, const Triangle &b) {
float s, area;
s = (b.x + b.y + b.z) / 2;
area = sqrt(s * (s - b.x) * (s - b.y) * (s - b.z));
// cout << "area is " << area << endl;
os << "area is " << area <<endl;
return os;
}
这样,打印的时候只要 cout << a + b << endl;即可
代码稍微改了下,具体的算法没看,
#include <iostream>
#include <math.h>
using namespace std;
class Triangle {
private:
int x, y, z;
public:
Triangle() { }
void area() {
float s, area;
s = (x + y + z) / 2;
area = sqrt(s * (s - x) * (s - y) * (s - z));
cout << "area is " << area << endl;
}
friend ostream &operator<<(ostream &os, const Triangle &b) {
float s, area;
s = (b.x + b.y + b.z) / 2;
area = sqrt(s * (s - b.x) * (s - b.y) * (s - b.z));
// cout << "area is " << area << endl;
os << "area is " << area <<endl;
return os;
}
friend Triangle operator+(Triangle left, Triangle right) {
Triangle b;
b.x = left.x + right.x;
b.y = left.y + right.y;
b.z = left.z + right.z;
return b;
}
void input() {
cin >> x >> y >> z;
}
void output() {
cout << "triangle three horizon length is " << x << " " << y << " " << z << endl;
}
};
int main() {
Triangle a, b, c;
a.input();
b.input();
c.input();
(a + b).output();
// (a + b).area();
cout << a + b + c <<endl;
return 0;
}
PS:
我更新了下,这里其实没必要用友元函数,直接如下用就行
Triangle operator+(Triangle other)
{
Triangle ret;
ret.x = this->x + other.x;
ret.y = this->y + other.y;
ret.z = this->z + other.z;
return ret;
}
你用friend来处理的话,返回值也是一个Triangle,可以递归的再去加另外一个Triangle,就实现多个Triangle连加的形式
这篇关于c++ - 友元函数运算符重载参数表中如何写多个参数一起进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文