how to overload unary operator '!' as member funtion

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#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;
}
Method operator! takes no arguments

1
2
3
4
bool operator!()
	{
		return (cx == 0 && cy == 0 && cz==0);
	}


Method
operator-
takes no argument in your implementation and concept
1
2
3
4
5
co_ordi operator-(){
 
// do some thing

}
Last edited on
Try removing the arguments for your operator functions. I believe this is implied as an argument if you write the function as a member of a class.
Topic archived. No new replies allowed.