Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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).
The << operator and any arithmetic is done by declaring functions outside the class
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question