S
S
sddvxd2018-03-26 18:41:26
C++ / C#
sddvxd, 2018-03-26 18:41:26

What is wrong here (operator overloading)?

class String{
private:
  static int num_strings;
public:
  int len;
  char* str;
  String(const char*);
  ~String();
  ostream& operator<<(ostream&)const;
};
int String::num_strings = 0;

String::String(const char* s){
  num_strings++;
  len = strlen(s);
  str = new char[len+1];
  strcpy(str,s);
  cout<<"string "<<str<<" created, "<<num_strings<<" strings left\n";
}



String::~String(){
  num_strings--;
  delete [] str;
  cout<<"object "<<str<<" deleted, "<<num_strings<<" strings left\n";
  
}

ostream& String::operator<<(ostream& os)const{
  os<<str;
  return os;
}
int main(){

  String s = "lolz";

  cout<<s;

  cin.get();
  return 0;
}

I know that the code is incorrect in terms of counting the number of elements and can corrupt memory when deleting objects, I just need to understand why when calling the overloaded << operator, the compiler gives a bunch of type incompatibility errors

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2018-03-26
@sddvxd

You have set up the String << ostream → ostream operation. It should be the other way around, ostream << string → ostream.
Such an operation can only be set up outside the class (perhaps as a friend).

A
Armenian Radio, 2018-03-26
@gbg

The << operator and any arithmetic is done by declaring functions outside the class

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question