0

只是在玩运算符重载,无法找出下面的代码有什么问题-

#include <iostream>

class Holder
{
public:
    std::string name;
    int data;
};

std::istream operator>>(std::istream& is, Holder &h)
{
    std::cout<<"Enter name = "<<std::endl;
    std::cin>>h.name;

    std::cout<<"Enter data = "<<std::endl;
    std::cin>>h.data;

    return is;
}

std::ostream operator<<(std::ostream& os, Holder const &h)
{
    std::cout<<"Name = "<<h.name<<std::endl;
    std::cout<<"Data = "<<h.data<<std::endl;

    return os;
}

int main(int argc, char **argv) {
    Holder h;
    std::cin>>h;
    std::cout<<h;
}

我的 MinGW 编译器给出的错误是 -

In file included from c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/ios:45:0,
                 from c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/ostream:40,
                 from c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/iostream:40,
                 from ..\src\Main.cpp:1:
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/ios_base.h: In copy constructor 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)':
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/ios_base.h:788:5: error: 'std::ios_base::ios_base(const std::ios_base&)' is private
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/basic_ios.h:64:11: error: within this context
In file included from c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/iostream:41:0,
                 from ..\src\Main.cpp:1:
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream: In copy constructor 'std::basic_istream<char>::basic_istream(const std::basic_istream<char>&)':
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/istream:57:11: note: synthesized method 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)' first required here 
..\src\Main.cpp: In function 'std::istream operator>>(std::istream&, Holder&)':
..\src\Main.cpp:18:9: note: synthesized method 'std::basic_istream<char>::basic_istream(const std::basic_istream<char>&)' first required here 
4

1 回答 1

2

通过引用返回:

std::istream& operator>>(std::istream& is, Holder &h)
std::ostream& operator<<(std::ostream& os, Holder const &h)
          //^

因为流是不可复制的。

于 2013-04-11T14:54:26.877 回答