Using std::copy - error C2679: can't find correct binary '=' operator

[亡魂溺海] 提交于 2020-01-15 10:42:58

问题


I am trying to use a solution from this question:

  • How do I iterate over cin line by line in C++?

The error message

c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(2144): error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const Line' (or there is no acceptable conversion)

(and a bunch of template trace data after this)

I am using Visual C++ 2010 Express.

The code

#include<string>
#include<iostream>
#include<fstream>
#include<vector>
#include<iterator>

class Line
{
  std::string data;

public:
  friend std::istream& operator>>(std::istream& inputStream, Line& line)
  {
    std::getline(inputStream, line.data);
    return inputStream;
  }

  operator std::string()
  {
    return data;
  }
};

int main(int argc, char* argv[])
{
  std::fstream file("filename.txt", std::fstream::in | std::fstream::out);
  std::vector<std::string> lines;

  // error is in one of these lines
  std::copy(
    std::istream_iterator<Line>(file),
    std::istream_iterator<Line>(),
    std::back_inserter(lines));
}

回答1:


Here is correct version that compiles fine :

class Line
{
    std::string data;

    public:
        friend std::istream& operator>>(std::istream& inputStream, Line& line)
        {
            std::getline(inputStream, line.data);
            return inputStream;
        }

        operator std::string() const
        {
            return data;
        }
};

The conversion operator needs to be const.




回答2:


I changed:

  operator std::string()

To

operator std::string() const

and it compiled fine.



来源:https://stackoverflow.com/questions/6302899/using-stdcopy-error-c2679-cant-find-correct-binary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!