2016-09-14 20 views
0

2つの単純なクラスがあります:integerとその中に変数intが1つあり、realdoubleです。完璧に働いC++:双方向のクラス変換

integer a=2016; int b=a;

real a=20.16; double b=a;

ように、私はまだ行っています。似た構文を持つ

integer foo; real bar; foo=bar; bar=foo;

あるいは、少なくとも:今、私はそうのように、それらの間の変換を行う必要があります。私はdoubleをintに変換するときにデータが失われることを知っています。私はそれに対処します。だから私はどうすればいいのですか?どこに#includeして、どのメソッド/演算子がオーバーロードして書くべきですか?私のプロジェクトは、ファイルmain.cppinteger.hinteger.cppreal.hreal.cppに分かれています。ありがとう。

EDIT:あなたは基本的に自分の問題には2つのソリューションを持っている

//integer.h 
class integer 
{ 
    private: 
     int a; 
    public: 
     integer(); 
     integer(int number); 
     operator int() const; 
}; 
//integer.cpp 
#include "integer.h" 

integer::integer(){ 
    a=0; 
} 
integer::integer(int number){ 
    a=number; 
} 
integer::operator int() const{ 
    return a; 
} 
//real.h 
class real { 
    private: 
     double a; 
    public: 
     real(); 
     real(double number); 
     operator double() const; 
}; 
//real.cpp 
#include "real.h" 

real::real(){ 
    a=0; 
} 
real::real(double number){ 
    a=number; 
} 
real::operator double() const{ 
    return a; 
} 
+1

http://en.cppreference.com/w/cpp/language/cast_operator – Danh

+0

良い答えを得るには、これらのクラスの最小限のバージョンを表示する必要があります。 –

+0

@erip継承はありません。この場合、[円 - 楕円問題](https://en.wikipedia.org/wiki/Circle-ellipse_problem)がありますか? –

答えて

2

:クラスのように見えます

最初はintegerオブジェクトにrealオブジェクトに変換することができますconversion operators、および副を書くことですその逆。

もう1つの解決策は、カスタムコンストラクタと代入演算子を実装してもう一方のクラスを実装することです。

+0

"説明"の最初の例のようにしようとしましたが、 "入れ子になった名前指定子で使用されている型が不完全"です。どのように2番目の変種を行うには? – 1valdis

+0

@ 1valdis変換演算子関数***宣言***のみをクラスに入れます。そして***は両方のクラスが完全に定義された後に***を定義する(すなわち実装する)。 –

+0

.cppで定義されたヘッダーに関数を宣言しました。他にどこでそれをするべきですか? – 1valdis