Can't I get it with a pointer when I overload the operator?

Asked 2 years ago, Updated 2 years ago, 18 views

Rect* r1 = new Rect(40);
Rect* r2 = new Rect(80);
cout << r1+r2 << endl;

I want to overload the class that I received with a pointer like this so that I can calculate it. So,

friend Rect &operator+(const Rect *r1, const Rect *r2);

I tried it like this, but it says I can't get it with a pointer. What should I do?

c++

2022-09-21 16:03

1 Answers

The operator of the pointer cannot be overloaded.

If it's absolutely necessary, you can make a light wrapper that wraps around the pointer. The concept is as follows.

class RectPtr {
public:
  RectPtr( Rect * ptr ):fPtr(ptr){;}
  Rect * operator->() const { return fPtr; };
  Rect operator+( const RectPtr &b ){
    return Rect( ... );
  }
  bool isNull(){ return fPtr == nullptr; }
private:
  Rect * fPtr = nullptr;
};
RectPtr r1 = new Rect(40);
RectPtr r2 = new Rect(80);

cout<< r1 +r2<<endl;


2022-09-21 16:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.