C++中的类到类数据类型转换

Class to Class Data Type Conversions in C++

本文关键字:数据 类型转换 C++      更新时间:2023-10-16

我正在自学如何用C++编程并解决这个问题:

编写一个具有Date类和Julian类的C++程序。Julian类应该将日期表示为长整数。对于此程序,请在Date类中包含一个转换运算符函数,该函数使用提供的算法将Date对象转换为Julian对象。通过转换2011年1月31日和2012年3月16日来测试您的程序,这两个日期对应于儒略历734533和734943。

因此,我们必须有一个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;
}

您需要在Date类之前定义Julian类。这里仅仅是正向声明是不起作用的,因为Date类需要Julian类的完整定义。