Reputation: 105
Here are the instructions verbatim:
String insertion/extraction operators (<< and >>) need to be overloaded within the MyString object. These operators will also need to be capable of cascaded operations (i.e., cout << String1 << String2 or cin >> String1 >> String2). The string insertion operator (>>) will read an entire line of characters that is either terminated by an end-of-line character (\n) or 256 characters long. An input line that exceeds 256 characters will be limited to only the first 256 characters.
With that, this is the code I've gotten thus far:
in my .cpp file:
istream& MyString::operator>>(istream& input, MyString& rhs)
{
char* temp;
int size(256);
temp = new char[size];
input.get(temp,size);
rhs = MyString(temp);
delete [] temp;
return input;
}
in my .h file:
istream& operator>>(istream& input, MyString& rhs);
call from main.cpp file:
MyString String1;
const MyString ConstString("Target string"); //Test of alternate constructor
MyString SearchString; //Test of default constructor that should set "Hello World"
MyString TargetString (String1); //Test of copy constructor
cout << "Please enter two strings. ";
cout << "Each string needs to be shorter than 256 characters or terminated by
/.\n" << endl;
cout << "The first string will be searched to see whether it contains exactly the second string. " << endl;
cin >> SearchString >> TargetString; // Test of cascaded string-extraction operator<<
The error that I get is: istream& MyString::operator>>(std::istream&, MyString&)â must take exactly one argument
How can I correct this? I am super confused on how to do this without BOTH the rhs and input
Upvotes: 0
Views: 2377
Reputation: 75150
You have to create the operator>>
as a non-member function.
As it is now, your function expects three arguments: the implicit invoking object, the istream&
, and the MyString& rhs
. However, since operator>>
is a binary operator (it takes exactly two arguments) this won't work.
The way to do this is to make it a non-member function:
// prototype, OUTSIDE the class definition
istream& operator>>(istream&, MyString&);
// implementation
istream& operator>>(istream& lhs, MyString& rhs) {
// logic
return lhs;
}
And doing it that way (non-member function) is the way you have to do all operators where you want your class to be on the right side, and a class that you can't modify on the left side.
Also note that if you want to have that function access private
or protected
members of your objects, you have to declare it friend
in your class definition.
Upvotes: 1