また、抽出子と挿入子はfriend関数定義に変更せよ。】
という課題が出たのですが2項演算子のオーバーロードも変換関数のオーバーロードもうまくいきません。
一応抽出子と挿入子を変更できていると思いますが、コードを乗せるのでアドバイスよろしくお願いします。
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
int gcm( int, int );
int lcm( int, int );
//分数クラスの定義
class Bunsu
{
int bunshi; //分子
int bunbo; //分母
public:
//デフォルトコンストラクタ
Bunsu() :
bunshi( 1 ),
bunbo( 0 )
{
}
//コンストラクタ
Bunsu( int b1, int b2 )
{
//約分をする
yakubun( b1, b2 );
}
//実数型のコンストラクタ
Bunsu( double a )
{
double d = a; //実数
int c,count; //実数の現在1桁目
count = 0;
while( true )
{
d *= 10.0;
c = (int)d;
count++;
if( d - c == 0 )
break;
}
//約分をする
yakubun( (int)d, (int)pow( 10, (double)count) );
}
//出力
void p_bunsu(void) const
{
cout << get_bunshi() << " / " << get_bunbo() << "\n";
}
//分子の値を返す
int get_bunshi(void) const
{
return bunshi;
}
//分母の値を返す
int get_bunbo(void) const
{
return bunbo;
}
//分子に代入
void set_bunshi(int b)
{
bunshi = b;
}
//分子に代入
void set_bunbo(int b)
{
bunbo = b;
}
//実数表示
void p_bunsu_f(void)
{
double bun = get_value();
cout << bun << "\n";
}
//実数を返す
double get_value(void)
{
return (double)bunshi / bunbo;
}
//実数を分数に変換して代入
void set_bunsu(double Bun)
{
double d = Bun; //実数
int c,count; //実数の現在1桁目
count = 0;
while( true )
{
d *= 10.0;
c = (int)d;
count++;
if( d - c == 0 )
break;
}
//約分をする
yakubun( (int)d, (int)pow( 10, (double)count) );
}
//約分をする
void yakubun( int si, int bo )
{
int yaku;
//最大公約数から約分をできるかを判定
if( bo > si )
yaku = gcm( bo , si );
else
yaku = gcm( si , bo );
if( yaku != 0 )
{
bunbo = bo / yaku;
bunshi = si / yaku;
}
}
//出力用のメンバ関数 (出力演算子のオーバーロード)
friend ostream& operator<<( ostream& , Bunsu& );
//入力用のメンバ関数 (入力演算子のオーバーロード)
friend istream& operator>>( istream& , Bunsu& );
//加算用のメンバ関数
friend Bunsu operator+( const Bunsu& );
//減算用のメンバ関数
friend Bunsu operator-( const Bunsu& );
//掛算用のメンバ関数
friend Bunsu operator*( const Bunsu& );
//除算用のメンバ関数
friend Bunsu operator/( const Bunsu& );
};
//最大公約数をユークリッドの互助法で求める関数
int gcm( int x, int y )
{
int r;
while( y != 0 ) //yの値が0以外のときに中でループを続ける
{
r = x % y;
x = y;
y = r;
}
return x;
}
ostream& operator<< ( ostream& s, Bunsu& a)
{
s << a.bunshi << " / " << a.bunbo << "\n";
return s;
}
istream& operator>> ( istream& i, Bunsu& d )
{
char ch;
i >> d.bunshi >> ch >> d.bunbo;
return i;
}
//加算用のメンバ関数
Bunsu Bunsu::operator+( const Bunsu& a )
{
}
//減算用のメンバ関数
Bunsu Bunsu::operator-( const Bunsu& a )
{
}
//掛算用のメンバ関数
Bunsu Bunsu::operator*( const Bunsu& a )
{
}
//除算用のメンバ関数
Bunsu Bunsu::operator/( const Bunsu& a )
{
}
/*---ここまでがクラスなどの定義部---*/
//メイン関数
int main()
{
double bunsu;
/*-----------分数で入力した場合の処理----------*/
//初期化
Bunsu a;
cout << "*****分数で入力します*****\n";
cout << "分数を入力してください";
cin >> a;
//入力した数を表示
cout << "分数を出力します:";
cout << a;
/*-----------実数で入力した場合の処理----------*/
cout << "*****実数で入力します*****\n";
cout << "実数を入力してください。";
cin >> bunsu;
//初期化
Bunsu b( bunsu );
//入力した数を表示
cout << "分数を表示:";
cout << b;
cout << "実数で表示:";
b.p_bunsu_f();
cout << "実数:" << b.get_value() << "\n";
}