2016-04-05 10 views
0

私のプログラムでは、2つのmoney値(クラス/コンストラクタの2つのインスタンスを作成)を受け入れることになっていますが、それらも比較する予定です。私はそれらを比較する方法、または使用するコンストラクタ(私は3つのオーバーロードコンストラクタがある)がわからない。 最初のif文がコメントアウトされたのは、値の比較をどのように考えていたかですが、書き込んだ時間と同じ時間displayMoney()を再現していました。 2番目のif文は、プログラムがユーザー入力に基づいて使用するコンストラクタを選択すると思った方法です。コンストラクタ/ oveloadingを使用することについてはごめんなさい。混乱します。コンストラクタを使用してユーザ入力を比較/計算する

相続人はこれまでのところ、私のコード:

#include <iostream> 
#include <string> 

using namespace std; 

class money 
{ 
private: 
    int dollars; 
    int cents; 
public: 
    money(); 
    money(int str); 
    money(int str1, int str2); 
    double displayMoney(); 
}; 

money::money() 
{ 
    dollars = 0; 
    cents = 0; 
} 
money::money(int str) 
{ 
    dollars = str; 
    cents = 0; 
} 
money::money(int str1, int str2) 
{ 
    dollars = str1; 
    cents = str2; 
} 

double money::displayMoney() 
{ 
    double total = dollars + cents/(double)100; 
    cout << "$" << total << endl; 
    return total; 
} 




int main() 
{ 

    int input11, input12, input21, input22; 

    money c; 

    cout << "Enter 2 money values: "<< endl; 
    cout << "\n Dollars 1: "; 
    cin >> input11; 
    cout << " Cents 1: "; 
    cin >> input12; 

    cout << "\n Dollars 2: "; 
    cin >> input21; 
    cout << " Cents 2: "; 
    cin >> input22; 

    money x(input11, input12); 
    money y(input21, input22); 

    /*if(x.displayMoney() > y.displayMoney()) 
    { 
     cout << "\n $" << x.displayMoney() << " is greater than " << "$" << y.displayMoney() << endl; 
    } 
    else if(x.displayMoney() < y.displayMoney()) 
    { 
     cout << "\n $" << y.displayMoney() << " is greater than " << "$" << x.displayMoney() << endl; 
    } 
    else 
    { 
     cout << "\n $" << x.displayMoney() << " is equal to " << "$" << y.displayMoney() << endl; 
    }*/ 


/*if (input1 > 0 && input2 > 0) 
    { 
     money x(input1, input2); 
     x.displayMoney(); 
    } 
    else if (input2 <= 0 && input1 > 0) 
    { 
     money x(input1); 
     x.displayMoney(); 
    } 
    else 
    { 
     money x; 
     x.displayMoney(); 
    }*/ 

    return 0; 
} 
+1

検索演算子のオーバーロード。 – user222031

答えて

0

次の2つの選択肢があります。 1つ以上の比較演算子をオーバーロードするか、1つの比較可能な値(合計セント)を返すメソッドを提供します。

オプション1:

class money { 
    //... 

    public: 
    bool operator< (const money & b) const { 
     return dollars < b.dollars || dollars == b.dollars && cents < b.cents; 
    } 
}; 

あなたは同様の方法でoperator>operator==を定義することができ、またはあなたがoperator<からそれらを得ることができます:

bool operator> (const money & a, const money & b) { return b < a; } 
bool operator== (const money & a, const money & b) { return !(a < b || b < a); } 

オプション2:

class money { 
    //... 

    public: 
     int totalCents() const { return dollars * 100 + cents; } 
}; 

"money"を1つの組み込み値に減らしたので、演算子のオーバーロードなしで実際の金額を比較できるようになりました。

関連する問題