gpt4 book ai didi

c++ - 运算符重载 : getting unidentifiable errors

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:29 25 4
gpt4 key购买 nike

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

在这个程序中,我重载了 + 和 << 运算符。但是当我试图替换 cout << item3 行时;用 cout << (item1+item2) ;或者 cout << 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)

这是怎么回事?

最佳答案

你实现了

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

对比

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

关于c++ - 运算符重载 : getting unidentifiable errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14195001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com