1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

how to overload unary operator '!' as member funtion

Discussion in 'C++' started by pushpat, Feb 14, 2012.

  1. pushpat

    pushpat New Member

    Joined:
    Feb 14, 2012
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    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::eek:perator!(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::eek:perator-(const co_ordi&)

    Code:
    #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;
    }
    
    
     

Share This Page