代码之家  ›  专栏  ›  技术社区  ›  Brian Hooper

C++好友运算符重载不编译

c++
  •  4
  • Brian Hooper  · 技术社区  · 14 年前

    #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\ n数字和to\ n字符串被认为是私有的,而读写是可以的?

    2 回复  |  直到 14 年前
        1
  •  5
  •   Péter Török    14 年前

    函数签名不同:

        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);
    
        2
  •  0
  •   msw    14 年前

    Pter Trk得到了答案,但在尝试阅读你的代码时,我被语法垃圾和过于相似的名字所困扰,我想这可能是困难的一部分。所以我做了:

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