Reputation: 22054
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.
Upvotes: 4
Views: 736
Reputation: 43487
Péter Török got the answer, but in trying to read your code, I got tangled up in syntactic junk and names which were too similar, which I expect may have been part of the difficulty. So I did:
s/std:://g
s/to_string/wilma/g
s/to_number/betty/g
which made the errors far more visible.
Upvotes: 0
Reputation: 116266
The function signatures are different:
friend std::string &operator << (std::string, const number &num);
friend std::string &operator >> (std::string, number &num);
are declared with a string
parameter by value, while
std::string & operator >> (std::string &s, number &num) ...
std::string & operator << (std::string &s, const number &num) ...
both have a string&
reference parameter. So the function you actually implement is not the same as the one declared as friend
- hence the error.
Try changing the friend declaration to
friend std::string &operator << (std::string&, const number &num);
friend std::string &operator >> (std::string&, number &num);
Upvotes: 5