我一直在Visual Studio中得到与我的程序的编译器错误快递13 我评论的2线在我的代码在编译器错误被显示出来运算符重载错误?
Date.cpp
#include "Date.h"
using namespace std;
Date::Date(int d, int m, int y) : day(d), month(m), year(y)
{}
Date::Date() : day(0), month(0), year(0)
{}
const int Date::getDay() { return day; }
const int Date::getMonth() { return month; }
const int Date::getYear(){ return year; }
bool Date::operator<(const Date dOther)
{
return (year < dOther.year) || (year == dOther.year && month < dOther.month)
|| (year == dOther.year && month == dOther.month && day < dOther.day);
}
string Date::toString() //Error: Declaration is incompatible with...declared at line 21...Date.h
{
string s = month + "-" + day; s+="-" + year;
return s;
}
ofstream& operator<<(ofstream& out, Date& d)
{
string s = d.toString();
out.write(s.c_str(), s.size());
return out;
}
void Date::operator=(string s) //no instance of overloaded function "Date::operator=" matches the specified type
{
stringstream stream;
stream << s;
stream >> month;
stream >> day;
stream >> year;
}
Date.h
#ifndef DATE_CLASS
#define DATE_CLASS
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
class Date
{
private:
int day, month, year;
public:
Date();
Date(int, int, int);
const int getDay();
const int getMonth();
const int getYear();
string toString();
bool operator<(const Date);
friend ofstream& operator<<(ofstream& out, Date&d);
void operator=(string);
};
#endif
我不知道为什么会出现这些错误。操作符重载是否是一个问题?或者什么与视觉工作室(由于某种原因,如果我删除Date.cpp中的一些代码,编译器错误消失)?
你应该在适当的时候在你的成员函数中使用'const',而不是返回'const'的东西,并且'operator ='返回一个'Date'。另外使'operator <<'带一个'const Date&'而不是朋友,因为它不需要在这里。可能只是做'out << s;'并且使用'std :: ostream&',所以它不仅仅适用于文件。 – chris
这是你的确切代码吗?你的头文件应该有错误。任何地方都不需要'std ::'。 – yizzlez
@chris为什么'operator <<'不是好友功能?我认为既然函数的第一个参数是'ostream',我就需要让这个函数成为朋友直接更改Date对象的成员变量 – AmitS