我尝试创建自己的类,其中包含三个变量:日、月和年。我添加了两个运算符进行比较。这是我的头文件和 cpp 文件:
标题:
#ifndef DATE_H
#define DATE_H
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <array>
using namespace std;
class Date {
public:
int day;
int month;
int year;
Date(int m, int d, int y);
bool operator< (const Date &) const;
bool operator== (const Date &) const;
}
#endif
CPP:
#include "stdafx.h"
#include "date.h"
Date::Date(int m, int d, int y)
:day(d),month(m),year(y){}
bool Date::operator< (const Date & d2) const
{
bool result;
if(year<d2.year){
result=true;
}
else if (year==d2.year&&month<d2.month){
result=true;
}
else if (month==d2.month&&day<d2.day){
result = true;
}
else{
result = false;
}
return result;
}
bool Date::operator== (const Date & d2) const
{
return (year==d2.year)&&(month==d2.month)&&(day==d2.day);
}
错误是
error C2533: 'Date::{ctor}' : constructors not allowed a return type
谢谢你的帮助!
最佳答案
类定义末尾没有分号。
其他评论:
为避免名称冲突(例如与
std::distance
),请勿放置using namespace std;
在 header 中的全局命名空间中。<stdafx.h>
是在您的 Visual Studio 项目中定义的非标准 header ,这使得该代码依赖于 Visual Studio。您可以通过在项目设置中关闭“预编译 header ”来避免它。
关于c++ - 无法创建我自己的日期类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626109/