D
D
Danil Vaskevich2021-06-15 11:00:24
C++ / C#
Danil Vaskevich, 2021-06-15 11:00:24

How to overload operator ++ for native String class?

I'm overloading the ++ operator for a String class that I wrote myself. Compile error C2676 binary "++": 'String' does not define this operator or cast to a type acceptable to the built-in operator. At first I thought that the problem was in the method declaration in the class, but everything is correct there. Here is the code:

String& String::operator++() {

  size_t length = strlen(this->string_);

  char tmp;
  String result(length);

  for (size_t i = 0; i < length; i++)
  {
    tmp = this->string_[0];
    tmp += 1;
    cout << tmp;
    result.string_[i] = tmp;
  }

  result.string_[length + 1] = '\0';
  
  return result;
}


Grateful for any help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2021-06-15
@DaniVffgf

In a prefix increment, you must change the current object and return a reference to itself.
You are generating a new object.

A
Alexander Ananiev, 2021-06-15
@SaNNy32

https://docs.microsoft.com/en-us/cpp/cpp/increment...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question