#ifndef DECIMAL_H
#define DECIMAL_H
#include
using std::ostream;
using std::istream;
class Decimal {
public:
friend istream &operator>>( istream &, Decimal & );
friend ostream &operator<<(ostream &, const Decimal & );
Decimal( double = 0.0 );
void setInteger( double );
void setDecimal( double );
Decimal &operator=( const Decimal );
const Decimal operator+( const Decimal );
Decimal &operator+=( Decimal );
Decimal operator++();
//Decimal &operator++( double );
Decimal &operator++( int );
bool operator==( const Decimal );
bool operator!=( const Decimal&right )
{
return ! (*this==right);
}
private:
// friend ostream &operator<<( const Decimal & );
double integer;
double decimal;
};
#endif
#include
using std::cout;
using std::cin;
#include
#include "decimal.h"
Decimal::Decimal( double num )
{
decimal = modf( num, &integer );
}
ostream & operator<<( ostream & output,const Decimal & d )
{
double dec = 0;
dec = floor( d.decimal * 100 );
if ( dec < 0 )
dec = 0 - dec;
if ( d.decimal != 0 ) {
output << floor( d.integer ) << ".";
if ( dec > 10 )
output << dec;
else
output << "0" << dec;
}
else
output << d.integer;
return output;
}
istream& operator>>( istream & input, Decimal & d )
{
double num;
cout << "Enter a number: ";
input >> num;
d.decimal = modf( num, &d.integer );
return input;
}
Decimal &Decimal::operator=( const Decimal d )
{
integer = d.integer;
decimal = d.decimal;
return *this;
}
void Decimal::setDecimal( double d ) { decimal = d; }
void Decimal::setInteger( double i ) { integer = i; }
const Decimal Decimal::operator+(const Decimal d )
{
Decimal result;
result.setDecimal( decimal + d.decimal );
result.setInteger( integer + d.integer );
if ( result.decimal >= 1 ) {
result.decimal = result.decimal - 1.0;
result.integer++;
}
else if ( result.decimal <= -1 ) {
result.decimal = result.decimal + 1.0;
result.integer--;
}
return result;
}
Decimal& Decimal::operator+=( Decimal d )
{
*this += d;
return *this;
}
Decimal Decimal::operator++()
{
integer++;
return *this;
}
Decimal &Decimal::operator ++(int )
{
Decimal temp = *this;
integer++;
return *this;
}
bool Decimal::operator==( const Decimal d )
{
return ( integer == d.integer && decimal == d.decimal );
}
#include
using std::cout;
using std::endl;
using std::cin;
#include "decimal.h"
int main()
{
Decimal test1, test2, test3( 1.234 );
cout << "Initial values:\n";
cout << test1 << endl << test2 << endl << test3
<< endl << endl;
cin >> test1 >> test2;
cout << "The sum of test1 and test2 is: "
<< test1 + test2 << endl;
test3 += ++test2;
cout << "\nfinal values:\n"
<< "test1 = " << test1 << endl
<< "test2 = " << test2 << endl
<< "test3 = " << test3 << endl;
if ( test1 != test3)
cout << "test1 and test3 are not equal to each other\n";
return 0;
}
你要问的问题是什么?