int转换运算符'类后跟int是非法的'返回类型的main应该是'int'而不是'class'

Ter*_*how 1 c++

我现在正在从一本书中自学C++,其中一个练习是编写一个类Date,它将它保存的日期转换为一个唯一的整数.但是,当我运行程序时,我无法弄清楚我得到的这个错误.我在C++ 2010上编程.

错误是:

error C2628: 'Date' followed by 'int' is illegal (did you forget a ';'?)

error C3874: return type of 'main' should be 'int' instead of 'Date'

奇怪的是我试图将我的主要改为"返回0"; 并且仍然会出现上述错误.有任何想法吗?

这是我的代码:

#include "stdafx.h"
#include <iostream>

using namespace std;



class Date{
private:
    int day, month, year; //declaring variables

public:

    //declare constructor
    Date(int inputDay=1, int inputMonth=1, int inputYear=2012)
    :day(inputDay), month(inputMonth),year(inputYear){};

    // declare conversion operator for integers
    operator int(){
        return year*10000+month*100+day;
    }
}



int main() {
    Date today(25,11,2012);
    return today;
    //doesn't matter if I delete above 2 lines and write return 0; both errors still occur
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 7

您需要;在类定义之后添加一个.

  • 哈尔该死的我是个小伙子 (2认同)