Hi everybody,
i was writing a small c++ class that uses a list as a data member , i then wrote a small print function to print the numbers in the list

#include <iostream>
#include <string>
#include <sstream>
#include <list>
using namespace std;
class A
{
private:
	list<int> number;
	string ConverttoS(int) const;
public:
	A();
	string print();
};

string A::ConverttoS(int input) const
{
	std::stringstream out;
	out << input ;
	return out.str();
}

string A::print() 
{
	string output = "";
	list<int>::iterator i;

	for(i = number.begin() ; i != number.end() ; ++i)
		output =  output + ConverttoS(*i);

	return output;
}

everything is working fine until i decided to set the print member function as a const , since it is not modifying anything and it is only calling const data members but when i did that , the compiler gave the following error:

error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class std::list<int,class std::allocator<int> >::const_iterator' (or there is no acceptable conversion)

error C2679: binary '!=' : no operator defined which takes a right-hand operand of type 'class std::list<int,class std::allocator<int> >::const_iterator' (or there is no acceptable conversion)

it is not a big deal i can simply remove the const keyword from the implementation and declaration and everthing will work fine , but i am only curious to know why this is happening

Edited 7 Years Ago by I_Empire: n/a

This is simple (I hope). You are using an iterator. The iterator allows the method to change the data.

Now since an iterator is a class and your compiler cannot know until link time that the iterator does not change the data, you compiler HAS to assume that the iterator does, hence it doesn't allow const to be added to print.


A simple way to get round this is to use const_iteraror.

Another way is this

std::string
A::print() const
{
   std::ostringstream oSS;
   copy(number.begin(),number.end(),
          std::ostream_iterator<int>(oSS,""));
    return oSS.str();
}

The later method avoids the convert to S construction that creates a number of stringstreams, and avoids having an explicit iterator. So is slightly more preferable to some peoples tastes.

Note: you have to add #include <iterator> , to your C++ file.

Edited 7 Years Ago by StuXYZ: n/a

Can you post your new non-compiling/non-running code please.

The only thing that I can think you might have done wrong is to forget to at const to both the declaration and the instance eg.

class A
{
    std::string print() const ; 
};

std::string
A::print() const
{
   std::string output;
    std::list<int>::const_iterator iterI;
  //...
   return output;
}
This question has already been answered. Start a new discussion instead.