Reading some documentation online I found that istream
class was part of C
long before the string
class was added. So the istream
design recognizes basic C
types such as double
and int
, but it is ignorant of the string
type. Therefore, there are istream
class methods for processing double
and int
and other basic types, but there are no istream
class methods for processing string
objects.
My question is if there are no istream
class methods for processing string
objects, why this program works and how ?
#include <iostream>
int main(void)
{
std::string str;
std::cin >> str;
std::cout << str << std::endl;
return 0;
}
CodePudding user response:
This is possible with the use operator overloading. As shown in the below example, you can create your own class and overload operator<< .
#include <iostream>
class Number
{
//overload operator<< so that we can use std::cout<<
friend std::ostream& operator<<(std::ostream &os, const Number& num);
int m_value = 0;
public:
Number(int value = 0);
};
Number::Number(int value): m_value(value)
{
}
std::ostream& operator<<(std::ostream &os, const Number& num)
{
os << num.m_value;
return os;
}
int main()
{
Number a{ 10 };
std::cout<<a<<std::endl;//this will print 10
return 0;
}
Similar to the class Number
shown above, the class std::string
makes use operator overloading in particular std::string
also overloads operator<<
.
You might ask "if there are no istream class methods for processing Number objects, why this(the above) program works and how ?"
And the answer to that would be because of operator overloading, in particular by overloading operator<<
.
CodePudding user response:
Because of operator overloading.
In your case, including iostream
will include string
, a specialization of basic_string
. And basic_string
has the non-member functions operator <<
and operator >>
defined.
Similarly, you can also overload operator <<
and operator >>
for your own custom type.
CodePudding user response:
Because std::string
overload the >>
and <<
operator to return the type std::istream
and std::ostream
How they overload it, you can look in this link that Mat gives.
You can create your own class and overload operators, too. Here is an example:
class MyClass
{
int numberOne;
double numberTwo;
public:
friend std::ostream& operator<<(std::ostream &out, const MyClass& myClass);
friend std::istream& operator>> (std::istream& in, MyClass& myClass);
};
// Since operator<< is a friend of the MyClass class, we can access MyClass's members directly.
std::ostream& operator<<(std::ostream &out, const MyClass& myClass)
{
out << myClass.numberOne << ' ' << myClass.numberTwo;
return os;
}
// Since operator>> is a friend of the MyClass class, we can access MyClass's members directly.
std::istream& operator>> (std::istream& in, MyClass& myClass)
{
in >> myClass.numberOne;
in >> myClass.numberTwo;
return in;
}
int main()
{
MyClass myClass;
std::cin >> myClass;
std::cout << myClass;
}