2014-06-21 104 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