Hi folks,
I am learning operator overloading concept in c++, wrote sample program to test overloading of unary operator '!' and '-'.
Code will work if i use them as friend function but not for member function. Can anybody tell where am i going wrong in function bool operator!(const co_ordi &a) and co_ordi operator-(const co_ordi &x); . Is that correct way to declare and define.

I am getting following error
Error:
op_ovld_unary.cc:18: error: ‘bool co_ordi::operator!(const co_ordi&)’ must take ‘void’
op_ovld_unary.cc: In function ‘int main()’:
op_ovld_unary.cc:45: error: no match for ‘operator!’ in ‘!a’
op_ovld_unary.cc:45: note: candidates are: operator!(bool) <built-in>
op_ovld_unary.cc:50: error: no match for ‘operator-’ in ‘-b’
op_ovld_unary.cc:22: note: candidates are: co_ordi co_ordi::operator-(const co_ordi&)

#include<iostream>
using namespace std;

class co_ordi
{
	int cx,cy,cz;
	public:
	co_ordi(int x=0,int y=0,int z=0):cx(x),cy(y),cz(z)
	{
		cout<<"in c_tor="<<cx<<cy<<cz<<endl;
	}
	void get_coordi()
	{
		cout<<"x="<<cx<<"y="<<cy<<"z="<<cz<<endl;
	}
 // friend co_ordi operator- (const co_ordi &a);
 // friend bool operator! (const co_ordi &a);
 bool operator!(const co_ordi &a)
	{
		return (a.cx == 0 && a.cy == 0 && cz==0);
	}
	co_ordi operator-(const co_ordi &x)
	{
		co_ordi k(-x.cx,-x.cy,-x.cz);
		return k;
	}
		     
};
/**co_ordi operator- (const co_ordi &x)
{
	cout<<"me minus"<<endl;
	return co_ordi(-x.cx,-x.cy,-x.cz);
}
bool operator! (const co_ordi &a)
{

	return (a.cx == 0 && a.cy == 0 && a.cz == 0);
}**/


int main()
{
	co_ordi a,b(4,5,6);

	if(!a)
	cout<<"a at origin"<<endl;
	else
		cout<<"a not at origin"<<endl;
	b.get_coordi();
    b =	-b;
    b.get_coordi();
	return 0;
}

op_ovld_unary.cc:18: error: ‘bool co_ordi::operator!(const co_ordi&)’ must take ‘void’

i.e. bool co_ordi::operator!() must not take const co_ordi& .

Thank you Caligulaminus :).. I made the changes and its working

bool operator!()
	{
		return (cx == 0 && cy == 0 && cz==0);
	}
	co_ordi operator-()
	{
		co_ordi k(-cx,-cy,-cz);
		return k;
	}
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.