0

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]()’

Edited by Alex_: n/a

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by mitrmkar
Featured Replies
  • 1

    [QUOTE=Alex_]Gives this error [I]undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Complex const&)'[/I][/QUOTE] This occurs because the [ICODE]Complex &[/ICODE] is [ICODE]const[/ICODE] - and you try to use [ICODE]non-const[/ICODE] methods on the [ICODE]Complex[/ICODE] object. By making the methods [ICODE]const[/ICODE], your current code will work, like so .. [code] class Complex{ ... int getRe() … Read More

0

Try to implement the following

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

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&)'

1

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.

Votes + Comments
Thank you very much!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.