2012-04-15 9 views
0

私はこの状況に遭遇しました。私は本当に面倒です。私は2つのクラスを持っています:時間12と時間24は、それぞれ12時間と24時間基準で時間を維持します。どちらも、他のタイプへの変換を処理する個々の変換関数を持つことになっています。しかし、最初に時刻12を宣言すると、time24クラスが後で宣言されるため、変換関数のプロトタイプの「time24」は未定義になります。では今私は何をしますか?私はそれを2番目のクラスの後で定義して定義することさえできません。んで、どうする?変換機能を含む厄介な状況?

class time12 
{ 
operator time24() //time24 is undefined at this stage 
{ 

} 
}; 

class time24 
{ 

}; 
+0

そして、あなたが作業しているどの言語? –

答えて

1

通常、C++には2種類のファイル、.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 
} 
2

あなたはC++でそれを定義せずにクラスを宣言することができます。

class time24; 

class time12 
{ 
operator time24() //time24 is undefined at this stage 
{ 

} 
}; 

class time24 
{ 

}; 
+0

私はそれを知らなかった、ありがとう – Nirvan

0

あなたが言語を指定しませんでした - あなたは、動的型付けされた言語を扱っている場合は、no THER EIS、Pythonなど、 をこのような問題 - 解析に(コンパイル)しない時間 - - は、他のタイプは、変換メソッドが呼び出されたときに、実行時に知られる必要があるので、次のコードが有効である:

class Time12(Time): 
    def toTime24(self): 
     return Time24(self._value) 

class Time24(Time): 
    def toTime12(self): 
     return Time12(self._value) 

「toTime24」メソッドが呼び出されるまでに、グローバル名「Time24」が適切なクラスとして定義されます。 C++で

- あなたは関数のプロトタイプとほとんど同じ働きをクラスのスタブを宣言することができます - ちょうど行います

class time24; 

class time12 
{ ... } 

class time24 
{ ... } 

を、これは他の静的型付け言語でどのように機能するかSHUREありません。

+0

今、あなたはタグを使わずに質問の先頭に言語を置いていましたが、とにかく、この答えをダイナミックなタイピング世界。 – jsbueno

+0

他の静的言語(java、c#)の人々がwikiへの回答をpromして、そこでの処理方法を追加することができます – jsbueno

関連する問題