我有一个用于声明该类的头文件,一个用于其方法定义的 cpp 文件和一个主源文件,主要是我包含了头文件,但编译器提示我没有定义他的方法。 .. 日期.h
#ifndef _DATE_
#define _DATE_
#include <iostream>
#include <exception>
#include <string>
using namespace std;
class date{
int day, month, year;
public:
date(int d, int m, int y) :day(d), month(m), year(y){}
int getDay() const{ return day; }
int getMonth() const { return month; }
int getYear() const { return year; }
bool operator==(const date& d) const{ return ((day == d.day) && (month == d.month) && (year == d.year)); }
bool operator>(const date& d) const;
bool operator<(const date& d) const { return !(*this>d || *this == d); }
ostream& print(ostream& os) const;
};
#endif
日期.cpp
#include "Date.h"
bool date::operator>(const date& d) const {
if (year > d.year) return true;
if (year < d.year) return false;
if (month>d.month) return true;
if (month < d.month) return false;
if (day>d.day) return true;
return false;
}
ostream& date::print(ostream& out) const {
if (day < 10) out << "0";
out << day << "/";
if (month < 10) out << "0";
out << month << "/";
out << year << endl;
return out;
}
ostream& operator<<(ostream& ot, const date& d) {
return d.print(ot);
}
主要.cpp
#include "Date.h"
int main() {
date d(17, 10, 1996);
cout << d;
return 0;
}
错误: 错误 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'date' (or there is no acceptable conversion) c:\users\aub\documents\visual studio 2013\projects\project22\project22\main.cpp 5
2 IntelliSense: no operator "<<" matches these operands
operand types are: std::ostream << date c:\Users\aub\Documents\Visual Studio 2013\Projects\Project22\Project22\main.cpp 5
我也尝试过在 date.h 中实现我的重载运算符<<,但没有成功...
我在头文件中声明 operator<< 后得到的错误是: 错误1 error LNK2005: "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class date const &)"(??6@YAAAV?$basic_ostream@DU?$char_traits@D@std @@@std@@AAV01@ABVdate@@@Z) 已经定义在Date.obj c:\Users\aub\documents\visual studio 2013\Projects\Project22\Project22\main.obj
错误 2 错误 LNK1169:找到一个或多个多次定义的符号 c:\users\aub\documents\visual studio 2013\Projects\Project22\Debug\Project22.exe 1
最佳答案
声明ostream& operator<<(ostream& ot, const date& d);
应该在标题中。
关于c++ - 为什么编译器无法在 .cpp 文件中找到方法定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751102/