Sep 30, 2010 at 1:00am UTC
ostream & operator<<(ostream & stream, String1 &sIn)
{
stream << sIn.str;
return stream;
}
When I compile this I get 2 Error messages which is down from the 12 I had 3 hours ago, but I have no idea where I am going wrong.
1. error C2065: 'str': undeclared identifier
2. error C2228:left of '.sIn' must have class/struct/union
Sep 30, 2010 at 1:25am UTC
It is a homemade string class Here is the rest of the code I have written:
#include<iostream>
using namespace std;
class String1
{
private:
char str[80];
public:
String1();
String1(char *);
void GetString(char *);
//concatenation
String1 operator+(String1 &);
//assignment
String1 operator=(String1 &);
friend ostream & operator<<(ostream & stream, String1 & sIn);
};
ostream & operator<<(ostream & stream, String1 &sIn)
{
stream <<str.sIn;
return stream;
}
String1 String1::operator+(String1 & sIn)
{
String1 temp(this->str);
strcat(temp.str, sIn.str);
}
String1 String1::operator =(String1 & sIn)
{
}
void String1::GetString(char * strBufPtr)
{
strcpy(strBufPtr, str);
}
String1::String1()
{
str[0] = 0;
}
String1::String1(char * strIn)
{
strcpy(str, strIn);
}
void main()
{
String1 S("Bob");
char buffer[20];
S.GetString(buffer);
cout << buffer;
String1 S1, S2("Bob"), S3("Jones");
S1 = S2;
//S1 = S2 + S3("Bob"), S3("Jones");
//String1 S1, S2("Bob");
cout << S1<< S1;
}
Sep 30, 2010 at 1:36am UTC
First post
ostream & operator<<(ostream & stream, String1 &sIn)
{
stream << sIn.str;
return stream;
}
Second post
ostream & operator<<(ostream & stream, String1 &sIn)
{
stream <<str.sIn;
return stream;
}
Did you get mixed up somewhere ? Is it sIn.str or str.sIn ?
Sep 30, 2010 at 2:00am UTC
1. error C2065: 'str': undeclared identifier
2. error C2228:left of '.sIn' must have class/struct/union
The error already point out your mistake.
You declare as String1& sIn so inside you should call it like sIn.str instead.
Sep 30, 2010 at 2:10am UTC
Then I get 2 new errors:
1.error C2143:syntax error:missing ',' before '.'
2.error C2039:'sIn' : is not a member of 'String1'
I tried to put a ',' before the '.' and I got more errors. I don't know how I got this lost.
Sep 30, 2010 at 3:50am UTC
Actually for C++ operator overloading, we tend to return a pointer to current object so we can do nested calls on itself.
E.g
String1& String1::operator+(String1 & sIn)
{
String1 temp(this->str);
strcat(temp.str, sIn.str);
//Doesn't return a value
return *this;
}
String1& String1::operator =(String1 & sIn)
{
// I think I erased this trying to do the rest. doesn't return a value
return *this;
}
Sep 30, 2010 at 4:10am UTC
String1& String1::operator =(String1 & sIn)
{
return *this
}
For efficiency sake, you should return reference to String1 instead of a new copy of String1.