I see two different formats for operator overloading for the operator () overload and the ostream << overload and would like to know why this is.
#include <iostream>
using namespace std;
class printData {
public:
std::string str = "hello";
operator std::string () const; // {return str;}
};
printData::operator std::string () const {return str;}
std::ostream& operator << (ostream& os, printData const& p){
return os << p.str;
}
int main(void) {
printData pd{};
//
std::string str2 = pd; // str2 = pd.str from operator() overload
std::cout << str2 << std::endl; // output "hello"
std::cout << pd << std::endl; // output "hello" (from ostream overload)
return 0;
}
The operator() overload has the return type std::string AFTER the keyword operator. The ostream overload has the return type ostream& BEFORE the keyword operator. Why are these overloads structured differently or am I missing something? Thank you in advance.