C ++ friend运算符重载不能编译

时间:2010-07-14 14:37:57

标签: c++

我有以下(缩减)类定义,它有编译错误。

#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被认为是私有的,但是读写都没问题?

谢谢。

2 个答案:

答案 0 :(得分:5)

功能签名不同:

    friend std::string  &operator << (std::string,     const number &num);
    friend std::string  &operator >> (std::string,           number &num);

按值声明string参数,而

std::string  & operator >> (std::string &s, number &num) ...
std::string  & operator << (std::string &s, const number &num) ...

都有一个string&引用参数。所以你实际实现的函数与声明为friend的函数不同 - 因此错误。

尝试将好友声明更改为

    friend std::string  &operator << (std::string&,     const number &num);
    friend std::string  &operator >> (std::string&,           number &num);

答案 1 :(得分:0)

PéterTörök得到了答案,但是在尝试阅读你的代码时,我纠结于语法垃圾和名字过于相似,我认为这可能是困难的一部分。所以我做了:

s/std:://g
s/to_string/wilma/g
s/to_number/betty/g

使错误更加明显。