我正在教自己如何用C++编程并解决这个问题:
因此,我们必须有一个Date
方法,该方法将参数转换为Julian
类。我了解这必须通过关键字operator
完成。我编写了一些代码,并收到以下错误消息:
ttt.cpp:34:7: error: incomplete result type 'Julian' in function definition
Date::operator Julian()
^
ttt.cpp:11:7: note: forward declaration of 'Julian'
class Julian; // Forward declaration
^
ttt.cpp:50:12: error: 'Julian' is an incomplete type
return Julian(long(365*year + 31*(month-1) + day + T - MP));
^
ttt.cpp:11:7: note: forward declaration of 'Julian'
class Julian; // Forward declaration
^
2 errors generated.
我不清楚此错误消息的含义。我包括一个前向声明,因为
Julian
是在Date
之后定义的。我的代码如下。我将不胜感激任何帮助。谢谢。#include <iostream>
#include <iomanip>
using namespace std;
/*
* Class to class conversion
*/
// CLASS DECLARATIONS=========================================================
class Julian; // Forward declaration
// "Date" Class Declaration------------------------------------------
class Date
{
private:
int month;
int day;
int year;
public:
Date(int=7, int=4, int=2012); // Constructor
operator Julian(); // Method to convert "Date" class to "Julian"
void showDate(); // print "Date"
};
// "Date" CLASS IMPLEMENTATION----------------------------
Date::Date(int mm, int dd, int yyyy)
{ // Constructor Method
month = mm;
day = dd;
year = yyyy;
}
Date::operator Julian()
{ // Method to convert "Date" class to "Julian"
int MP, YP, T;
if( month <=2 )
{
MP = 0;
YP = year - 1;
}
else
{
MP = int(0.4*month + 2.3);
YP = year;
}
T = int(YP/4) - int(YP/100) + int(YP/400);
return Julian(long(365*year + 31*(month-1) + day + T - MP));
}
void Date::showDate()
{
cout << setfill('0')
<< setw(2) << month << '/'
<< setw(2) << day << '/'
<< setw(2) << year % 100;
}
// "Julian" CLASS DECLARATION--------------------------------------------------------
class Julian
{
private:
int days;
public:
Julian(long=0); // Constructor
void show(); // Print julian date
};
// "Julian" Class Implementation----------------------------------------------------
Julian::Julian(long d)
{
days = d;
}
void Julian::show()
{
cout << days << endl;
}
int main()
{
Date a(1,31,2011);
Date b(3,16,2012);
Julian c, d;
c = Julian(a);
d = Julian(b);
a.showDate();
c.show();
cout << endl;
b.showDate();
d.show();
cout << endl;
return 0;
}
最佳答案
您需要在Julian
类之前定义Date
类。只是前向声明在这里不起作用,因为Date
类需要Julian
类的完整定义。