流重载

magichuang magichuang 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我现在想用流重载输出CDate类,如果我把实现放在Date.cpp或main函数文件里,就没有问题
但是如果我把实现放在Date.h文件下就会出问题。

如果我这样写:
#include <iostream>
using namespace std;


#if !defined(AFX_DATE_H__91F06C7A_00D0_410C_86AE_0C76D3E71326__INCLUDED_)
#define AFX_DATE_H__91F06C7A_00D0_410C_86AE_0C76D3E71326__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CDate
{
friend ostream& operator<<( ostream&, const CDate& );
public:
CDate(int = 2008, int = 1 ,int = 1);
CDate(const CDate &);
void setDate(int, int, int);
void setYear(int );
void setMonth( int );
void setDay ( int );
int getYear() const;
int getMonth() const;
int getDay() const;
bool isLeapYear( int ) const;
void nextDay();
virtual ~CDate();
private:
int year, month, day;
int checkDays( int, int , int);

};
ostream& operator<< ( ostream& output, const CDate& d)
{
output<< "Year: " << d.getYear() << " Month: " << d.getMonth() << " Day: " << d.getDay() << endl;
return output;
}


提示错误 :这一行 cout << birthday;错误error C2593: 'operator <<' is ambiguous


如果我单写using std::ostream;
using std::cout;
using std::endl;
也在.h文件中,错误:
Student.obj : 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 CDate const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@
std@@AAV01@ABVCDate@@@Z) already defined in Date.obj
Test_CStudent_main.obj : 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 CDate const &)" (??6@YAAAV?$basic_ostream@DU?$char_trai
ts@D@std@@@std@@AAV01@ABVCDate@@@Z) already defined in Date.obj
Debug/Test_CStudent.exe : fatal error LNK1169: one or more multiply defined symbols found

麻烦高手给解释一下这两种错误是什么原因还有为什么会造成这两种错误。
...全文
评论 8
收藏 已收藏
分享
返回顶部
magichuang
C++ 语言 65,214 成员 250,514 内容