Home  >  Q&A  >  body text

c++ - 友元函数运算符重载参数表中如何写多个参数一起进行操作

PHP中文网PHP中文网2714 days ago549

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 13:48:26

    Normally (a + b).area(); is not called like this, it is unnatural to use.
    Instead, an overloaded function similar to the following will be implemented

        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;
        }
        

    In this way, when printing, just cout << a + b << endl;
    The code has been slightly changed, but I haven’t seen the specific algorithm,

    #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:
    I updated it. There is actually no need to use friend functions here, just use them as follows

    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;

    }

    If you use friend to handle it, the return value will also be a Triangle. You can recursively add another Triangle to achieve the form of adding multiple Triangles together

    reply
    0
  • Cancelreply