我一直在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