简体   繁体   中英

How to use both member function and friend function operator overloading in same class

As per an assignment requirement,

I am trying to implement prefix ++ and postfix ++ operator overloading both as member function and friend function in same class.

class dist {
private:
    int kMeter;
    int meter;
public:
    // postfix
    dist operator++(int unused) {
        dist dd = *this; 
        (this -> meter)++;
        return dd;
    }

    // prefix
    dist operator++() {
        ++(this -> meter);
        return *this;
    }

    dist(int k = 0, int m = 0) {
        kMeter = k;
        meter = m;
    }

    void print();
    int getMeter() const { return meter; }
    int getKMeter() const { return kMeter; }

    friend dist operator++(dist& d, int unused); //postfix
    friend dist operator++(dist& d); // prefix
};

dist operator++(dist& d, int unused) { // postfix friend func
    dist dd = d; // copy the old value into dd
    d.meter++;
    return dd; // return the original value of d
}

dist operator++(dist& d) { // friend prefix ++
    ++d.meter;
    return d; // return the final value of d
}

But when I trying to use prefix ++ or postfix ++ overloading it shows ambiguous error.

dist d2(1, 900);
dist d3(3, 800);

/// these following lines showing ambiguous error
cout << d2++ << endl;
cout << ++d3 << endl;

Now,

How can I use both type of operator overloading for same operator in same class file without getting any error.

Most operators can be overloaded either as member or nonmember function. Some operators ( = [] () -> ) can be overloaded only as members. But you cannot have any oeprator both as a member and nonmember, specifically because it is unclear how to pick either one of them.

What the assignment wants is probably:

  • you overload prefix ++ as a member and the postfix ++ as a nonmember (in your case, also friend)
  • create two separate programs: in one, those operators are overloaded as members, in another - as nonmembers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM