Box It!
`class Box{
public:
Box(){
l=b=h=0;
}
Box(int l,int b,int h)
{
this->l=l;
this->b=b;
this->h=h;
}
Box(Box&box)
{
this->l=box.l;
this->b=box.b;
this->h=box.h;
}
int getLength()
{
return l;
}
int getBreadth()
{
return b;
}
int getHeight()
{
return h;
}
long long CalculateVolume()
{
return static_cast
}
bool operator<(Box& box)
{
if (l < box.l) return true;
if (l == box.l && b < box.b) return true;
if (l == box.l && b == box.b && h < box.h) return true;
return false;
}
private:
int l;
int b;
int h;
};
ostream& operator<<(ostream& out, Box& B)
{
out<<B.getLength()<<' '<<B.getBreadth()<<' '<<B.getHeight();
return out;
}`
类型安全优化
`#include
using namespace std;
class Box {
private:
int l, b, h;
public:
Box() : l(0), b(0), h(0) {}
Box(int l, int b, int h) : l(l), b(b), h(h) {}
Box(const Box& box) : l(box.l), b(box.b), h(box.h) {}
int getLength() const { return l; }
int getBreadth() const { return b; }
int getHeight() const { return h; }
long long CalculateVolume() const {
return static_cast<long long>(l) * b * h;
}
bool operator<(const Box& box) const {
if (l < box.l) return true;
if (l == box.l && b < box.b) return true;
if (l == box.l && b == box.b && h < box.h) return true;
return false;
}
friend ostream& operator<<(ostream& out, const Box& B);
};
// 输出重载
ostream& operator<<(ostream& out, const Box& B) {
out << B.getLength() << ' ' << B.getBreadth() << ' ' << B.getHeight();
return out;
}
`

浙公网安备 33010602011771号