我遇到了这种情况,我发现确实很棘手。我有2类:time12和time24,它们分别在12小时和24小时的基础上维护时间。他们都应该具有单独的转换功能,以处理到另一种类型的转换。但是,如果我先声明时间12,则转换函数原型中的“ time24”将不确定,因为稍后将声明time24类。那我现在该怎么办?我什至不能只在第二个类之后声明它并在内部定义它。那么现在怎么办?
class time12
{
operator time24() //time24 is undefined at this stage
{
}
};
class time24
{
};
最佳答案
通常在c ++中,您有两种文件类型:.h和.cpp。您的.h文件是您的声明,而.cpp是您的定义。
例:
convtime.h:
#ifndef CONVTIME_H_ //this is to prevent repeated definition of convtime.h
#define CONVTIME_H_
class time24; //for the operator in class12
class time12
{
public:
time12(int); //constructor
operator time24();
private:
//list your private functions and members here
}
class time24
{
public:
time24(int); //constructor
private:
//list your private functions and members here
}
#endif //CONVTIME_H_
convtime.cpp:
#include "convtime.h"
//constructor for time12
time12::time12(int n)
{
//your code
}
//operator() overload definition for time12
time24 time12::operator()
{
//your code
}
//constructor for time24
time24::time24(int n)
{
//your code
}