C++PP 11-6

来源:互联网 发布:网络公选课是什么意思 编辑:程序博客网 时间:2024/05/04 17:37

//stonewt.h


#ifndef STONEWT_H_

#define STONEWT_H_


class Stonewt
{
private:
enum{ Lbs_per_stn = 14 };
int m_stone;
double m_pds_left;
double m_pounds;
public:
Stonewt(double lbs);
Stonewt(int stn, double lbs);
Stonewt();
~Stonewt();
void show_lbs() const;
void show_stn() const;
//重载 +,-,*,/,<,>,运算符
Stonewt & operator+(const Stonewt & s);
Stonewt & operator-(const Stonewt & s);
Stonewt & operator*(const Stonewt & s);
Stonewt & operator/(const Stonewt & s);
bool operator<(const Stonewt & s);
bool operator>(const Stonewt & s);
};

#endif

//stonewt.cpp

#include "stdafx.h"
#include <iostream>
#include "stonewt.h"
using std::cout;


//////
//构造函数 
//析构函数
/////
Stonewt::Stonewt(double lbs)
{
m_stone = int(lbs) / Lbs_per_stn;
m_pds_left = int(lbs) / Lbs_per_stn + lbs - int(lbs);
m_pounds = lbs;
}
Stonewt::Stonewt(int stn, double lbs)
{
m_stone = stn;
m_pds_left = lbs;
m_pounds = stn * Lbs_per_stn + lbs;
}
Stonewt::Stonewt()
{
m_stone = m_pounds = m_pds_left = 0;
}
Stonewt::~Stonewt()
{


}
///////
//构造函数
//析构函数
///////


void Stonewt::show_stn() const
{
cout << m_stone << " stone, " << m_pds_left << "pounds\n";
}


void Stonewt::show_lbs() const
{
cout << m_pounds << " pounds\n";
}


/////////
//重载 + - * / < > 运算符
/////////
Stonewt & Stonewt::operator+(const Stonewt & s)
{
m_pounds += s.m_pounds;
return *this;
}


Stonewt & Stonewt::operator-(const Stonewt & s)
{
m_pounds -= s.m_pounds;
return *this;
}


Stonewt & Stonewt::operator*(const Stonewt & s)
{
//return m_pounds *= s.m_pounds;  //返回类型为Stonewt,不能返回整个
m_pounds *= s.m_pounds;
return *this;
}


Stonewt & Stonewt::operator/(const Stonewt & s)
{
m_pounds /= s.m_pounds;
return *this;
}


bool Stonewt::operator<(const Stonewt & s)
{
if (m_pounds < s.m_pounds)
return true;
else
return false;
}


bool Stonewt::operator>(const Stonewt & s) 
{
if (m_pounds > s.m_pounds)
return true;
else
return false;
}


//main


#include "stdafx.h"
#include "stonewt.h"
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{
Stonewt s[6] =
{
Stonewt(2),
Stonewt(8, 2.3),  //类数组使用逗号分隔
Stonewt()         //其余的执行默认构造函数
};                    //对象数组结尾要使用分号
Stonewt ss;
//ss = s[1] + s[2];
//s[1].show_lbs();
//s[2].show_lbs();
//ss.show_lbs();
int n = s[0] < s[1] ? 1 : 0;
std::cout << n << std::endl;
system("pause");
return 0;
}

0 0
原创粉丝点击