I am trying to write my own string class but I have trouble writing:
operator<<
operator>>
How do I access ostream and istream?
Please help?
Printable View
I am trying to write my own string class but I have trouble writing:
operator<<
operator>>
How do I access ostream and istream?
Please help?
Declare them as friend functions of your class. The function prototypes might be like this:
for some class T for which these are friend functions.Code:std::ostream& operator<<(std::ostream&, const T&);
std::istream& operator>>(std::istream&, T&);
thanx laserlight but it didnt really work, maybe you can explain it to me a little more
The custom inserter and extractor can be as simple as this:
Code:#include <iostream>
#include <iomanip>
#include <cstring>
class String {
char *mem;
int size;
public:
String ( const char *p );
~String();
friend std::istream& operator>> ( std::istream& is, String& s );
friend std::ostream& operator<< ( std::ostream& os, const String& s );
};
String::String ( const char *p )
{
size = strlen ( p );
mem = new char[size + 1];
strcpy ( mem, p );
}
String::~String() { delete [] mem; }
std::istream& operator>> ( std::istream& is, String& s )
{
return is.getline ( s.mem, s.size );
}
std::ostream& operator<< ( std::ostream& os, const String& s )
{
return os << s.mem;
}
int main()
{
String s = "My cool string";
std::cout << s << "\nEnter a string: ";
std::cin >> s;
std::cout << s << '\n';
}