C++ C++<&书信电报;使用ostream重载以获得正确的格式

C++ C++<&书信电报;使用ostream重载以获得正确的格式,c++,overloading,ostream,C++,Overloading,Ostream,我已经开始编写自己的链接列表,它可以很好地打印数字,但我使用模板来确定用于对象的typename。因此,除了打印对象之外,我在输入数据时没有任何问题。我在这些类中遇到以下错误,但VisualStudio2010没有给出行号。我所要做的就是允许不同类型的对象以正确的格式从链接列表中输出 error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl ope

我已经开始编写自己的链接列表,它可以很好地打印数字,但我使用模板来确定用于对象的typename。因此,除了打印对象之外,我在输入数据时没有任何问题。我在这些类中遇到以下错误,但VisualStudio2010没有给出行号。我所要做的就是允许不同类型的对象以正确的格式从链接列表中输出

error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > &
__cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,
class Customer &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAVCustomer@@@Z)
already defined in Customer.obj
错误LNK2005:“类标准::基本类”&

__cdecl运算符在将函数定义放入头文件时要小心。您要么需要内联定义,要么最好将其放入
.cpp
文件中。在
Customer.h
中,只需放入函数原型即可:

// Customer.h
std::ostream& operator << (std::ostream& output, Customer& customer);
或者,如果您确实希望在头文件中包含定义,请添加
inline
关键字。内联定义必须包含在头文件中,而且本质上它们没有外部链接,不会触发重复的定义错误

inline std::ostream& operator << (std::ostream& output, Customer& customer)
{
    ...
}

inline std::ostream&operator您无法获取行号,因为直到
链接时间,链接器看不到任何源代码。问题是
您已将函数定义放在标题中;这只是
如果函数是函数模板或已声明,则为合法
inline
。通常的过程是在 并将定义与类放在同一源文件中
成员函数定义。

您是否已模板化了我没有意识到我是在Java背景下这么做的,我知道我是如何犯下这个错误的。谢谢,您解决了我的问题。
// Customer.h
std::ostream& operator << (std::ostream& output, Customer& customer);
// Customer.cpp
std::ostream& operator << (std::ostream& output, Customer& customer)
{
    output << "First Name: " << customer.getFirstName() << " "
           << "Last Name: "  << customer.getLastName()  << std::endl;
    return output;
}
inline std::ostream& operator << (std::ostream& output, Customer& customer)
{
    ...
}