0
#include <iostream>
using namespace std;

class sales_item  
{  
    friend ostream& operator<<(ostream&,const sales_item&);

public:

    int item;
    sales_item()
    {
        item=2;
    }
    sales_item operator+(sales_item& item1)
    {
        sales_item item2;
        item2.item = item1.item+item;
        return item2;
    }
};



ostream& operator<<(ostream &out, sales_item& item3)  
{

    out<<item3.item;
    return out;
}

int main(int argc, const char * argv[])  
{  
    sales_item item1,item2;
    sales_item item3=(item1+item2);
    cout<<item3;
    return 0;
}

in this program i am overloading the + and << operators. but when im trying to replace the line cout << item3 ; with cout << (item1+item2) ; or cout << item1+item2 ;

i am getting the following errors :

Undefined symbols for architecture x86_64:
  "operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, sales_item const&)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

How is it happening?

1
  • 2
    How are the errors unknown if you posted them? Commented Jan 7, 2013 at 11:31

2 Answers 2

6

You implemented

ostream& operator<<(ostream &out, sales_item& item3)  

vs

friend ostream& operator<<(ostream&,const sales_item&);
//                                    ^
//                        const is missing in definition
Sign up to request clarification or add additional context in comments.

2 Comments

i removed the const at both the places. still i got an error. : invalid operands to the binary expression.
@jithinc don't remove const - the signature should be ostream& operator<<(ostream &out, const sales_item& item3) in both places.
0

hey the error was because i was referencing the sales item in the function ostream& operator<<(ostream &out,sales_item &item3); when i removed the & it started working fine.. thanks

1 Comment

But it's (most likely) not doing what you want it to. It's now creating a copy when calling the function. Just as Luchian said, you should have const & in both places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.