S
S
Sergo Zar2021-10-02 20:23:48
C++ / C#
Sergo Zar, 2021-10-02 20:23:48

Is it possible to overload the postfix form of the ++ operator without using classes?

I want to overload the postfix form of the ++ operator for a variable of type string.

Tried like this:

the code
string operator ++ (string s){
  return s+"\n";
}
int main(){
  string text = "text";
  cout << ++text; 
}

but it turns out to overload only the prefix form ++.

I tried to google how to overload the postfix form but found only options using classes. It turned out something like this:
the code
class S{
  public:
   string s;
 
   S(string _s){
        s = _s;
   }

   S operator ++ (int hz){
        s += "\n";
        return *this;
   }
 
};

int main()
{
    S n("text");
    n++;
    cout << n.s ;  
}


In this case, it worked, but is there really no option without using classes (well, at least similar to my first option for the prefix form)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Prilepsky, 2021-10-02
@Sergomen

string operator ++ (string s, int){
return s+"\n";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question