about operator overloading

Discussion in 'C++' started by T.C, Nov 28, 2007.

  1. T.C

    T.C New Member

    Joined:
    Nov 26, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi there, I think this my first time :)

    For while I was working in learning Operator overloading but I still can’t figure it out.
    I did try several times by using different codes from various materials but still!!
    And this is one of my trial which doesn't work, so please if you don’t mind giving some tips on dealing with operator overloading and tell me what is the wrong with the code;!

    note: I did a search in the site about the issue before request my demand.

    Code:
    #include <iostream>
    using namespace std;
    
    using std::ostream;
    class Number{
    
    	friend ostream &operator<<(ostream &, const Number &);
    public:
    	Number();
    	void setN(int);
    	int getN()const;
    
    	Number operator+(const Number &)const;
    
    private:
    	int number;
    };
    
    Number::Number(){number=0;}
    void Number::setN(int n){number=n;}
    int Number::getN()const {return number;}
    
    ostream &operator<<(ostream &output, const Number &num)
    {
    	output<<num.number;
    	return output;
    }
    
    Number Number::operator +(const Number &other)const
    {
    	return  *this + Number(other);
    }
    
    int main()
    {
    	Number n1,n2;
    	Number sum;
    	
    	
    	n1.setN(3);
    	n2.setN(4);
    	cout<<": "<<n1.getN()<<endl;
    	cout<<": "<<n2.getN()<<endl;
    	sum= n1+n2;
                   cout<<sum<<endl;
    	
    	return 0;
    }
    
    errors I got:
    1.cannot access private member declared in class 'Number'
    2. see declaration of 'number'
    3. operator <<' is ambiguous
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Your << operator is a private function because class default specifier is private by default.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice