I have the following (cut-down) class definition, and it has compilation errors.
#include <iostream>
#include <string>
class number
{
public:
friend std::ostream &operator << (std::ostream &s, const number &num);
friend std::string &operator << (std::string, const number &num);
friend std::istream &operator >> (std::istream &s, number &num);
friend std::string &operator >> (std::string, number &num);
protected:
private:
void write ( std::ostream &output_target = std::cout) const;
void read ( std::istream &input_source = std::cin);
void to_string ( std::string &number_text) const;
void to_number (const std::string &number_text);
};
std::istream & operator >> (std::istream &s, number &num)
{
num.read (s);
return s;
}
std::string & operator >> (std::string &s, number &num)
{
num.to_number (s);
return s;
}
std::string & operator << (std::string &s, const number &num)
{
num.to_string (s);
return s;
}
std::ostream & operator << (std::ostream &s, const number &num)
{
num.write (s);
return s;
}
When I compile it, I get the following errors…
frag.cpp: In function ‘std::string& operator>>(std::string&, number&)’:
frag.cpp:17: error: ‘void number::to_number(const std::string&)’ is private
frag.cpp:27: error: within this context
frag.cpp: In function ‘std::string& operator<<(std::string&, const number&)’:
frag.cpp:16: error: ‘void number::to_string(std::string&) const’ is private
frag.cpp:32: error: within this context
Could anyone help with this; in particular why to_number and to_string are thought private but read and write are OK?
Thank you.
The function signatures are different:
are declared with a
stringparameter by value, whileboth have a
string&reference parameter. So the function you actually implement is not the same as the one declared asfriend– hence the error.Try changing the friend declaration to