我有以下(简化版)类定义,但它存在编译错误。
#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;
}
当我编译它时,我会得到以下错误...
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
有人能帮忙解决这个问题吗?特别是为什么 to_number 和 to_string 被认为是私有的,但 read 和 write 却可以使用?
谢谢。