I'm trying to make the container to work with one of my classes. But i don't understand what should the overloaded operator contain. Maybe this is because i don't know the container too well... Please give me some insights.

This is my class

class Complex{
private:
	int re;
	int im;
public:
	void init(int _re, int _im){
		re= _re;
		im= _im;
	}
	Complex(int _re, int _im){
		init (_re, _im);
	}
	int getRe(){
		return re;
	}
	int getIm(){
		return im;
	}
	void setRe(int _re){
			re = _re;
		}
	void setIm(int _im){
		im = _im;
	}
};

This is what i'm trying to do.

for(cpos = m3->begin();cpos !=m3->end(); cpos++){
	cout<< *cpos << ' ';
}

where m3 is of type multiset<Complex>*
and cpos is multiset<Complex>::iterator*

and this is the error:
no match for ‘operator<<’ in ‘std::cout << cpos.std::_Rb_tree_const_iterator<_Tp>::operator* [with _Tp = Complex]()’

Recommended Answers

All 3 Replies

Try to implement the following

class Complex
{
...
  // friend - allows access to private members
  friend ostream & operator << (ostream &, const Complex &);
...
};

OK , i did the following

class Complex{
//....
	friend ostream & operator<<(ostream &, const Complex &);
};
ostream & operator<<(ostream & os, Complex & it){
	os<<"re:"<<it.getRe()<<" im:"<<it.getIm()<<"| "<<endl;
}

Gives this error
undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Complex const&)'

Gives this error
undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Complex const&)'

This occurs because the Complex & is const - and you try to use non-const methods on the Complex object.
By making the methods const , your current code will work, like so ..

class Complex{
...
  int getRe() const {
...
  int getIm() const {
...
  friend ostream & operator << (ostream &, const Complex &);
};

Furthermore, since the operator overload is friend, you can directly access the member variables (no need to call the methods), like so ..

os << "re:" << it.re << " im:" << it.im << "| " << endl;

Regarding usage of const , I'd suggest that you read about const correctness.

commented: Thank you very much! +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.