运算符重载:出现无法识别的错误

时间:2013-01-07 11:30:18

标签: c++ operator-overloading

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

在这个程序中,我正在重载+和&lt;&lt;运营商。但当我试图替换线cout&lt;&lt; item3;与cout&lt;&lt; (item1 + item2);或者cout&lt;&lt; item1 + item2;

我收到以下错误:

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)

怎么回事?

2 个答案:

答案 0 :(得分:6)

您已实施

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

VS

friend ostream& operator<<(ostream&,const sales_item&);
//                                    ^
//                        const is missing in definition

答案 1 :(得分:0)

嘿,错误是因为我在功能中引用了销售项目 ostream的和放;运营商&lt;&lt;(ostream&amp; out,sales_item&amp; item3);当我删除&amp;它开始工作正常..谢谢