2014-06-21 39 views
1

我一直在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中的一些代碼,編譯器錯誤消失)?

+1

你應該在適當的時候在你的成員函數中使用'const',而不是返回'const'的東西,並且'operator ='返回一個'Date'。另外使'operator <<'帶一個'const Date&'而不是朋友,因爲它不需要在這裏。可能只是做'out << s;'並且使用'std :: ostream&',所以它不僅僅適用於文件。 – chris

+1

這是你的確切代碼嗎?你的頭文件應該有錯誤。任何地方都不需要'std ::'。 – yizzlez

+0

@chris爲什麼'operator <<'不是好友功能?我認爲既然函數的第一個參數是'ostream',我就需要讓這個函數成爲朋友直接更改Date對象的成員變量 – AmitS

回答

0

您的名稱空間不匹配。在標題中,您不要在string之前使用std命名空間前綴,因此編譯器無法找到您需要的類型string

+0

讓我想知道主文件或其他文件中有什麼可怕的東西。 – chris

+0

但是'ofstream'很好。真的讓我想知道...... – yizzlez

+0

@awesomeyi'ofstream'在頭文件中被引用並且在'toString'實現之後實際訪問它的內部元素。可以讓編譯器更容易使用引用類型,而不是在實際使用之前嘗試對它們進行評估(或者OP只是不包含其他錯誤......) – SomeWittyUsername