c++ - 友元函数运算符重载参数表中如何写多个参数一起进行操作
PHP中文网
PHP中文网 2017-04-17 13:46:26
0
1
587
PHP中文网
PHP中文网

认证0级讲师

répondre à tous(1)
大家讲道理

一般不会(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连加的形式

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal