作业:
使用提供的 Alien.h 文件实现 Alien 类。在这种情况下,外星人是根据他/她的身高、体重和性别来描述的。要比较两个外星人,您可以使用以下等式确定外星人的 statusPoints 值: statusPoints = weight * height * genderValue 其中,如果外星人是男性,genderValue 为 2,如果外星人是女性,则为 3。状态点应在需要时计算,而不是作为数据成员保存。这避免了所谓的陈旧数据,其中一个数据成员(例如权重)可能会更改,而状态点变量不会得到更新。比较外星人时应使用身份。您需要重载 ==、!=、>、<、>= 和 <= 运算符来比较外星人。因此,您可能有如下语句: if(alien1 >
显然,alien1 将是 Alien 对象,alien2 也是如此。还假设他们的数据成员(身高、体重和性别)已初始化。
这是提供的 .h 文件。同样,我无法更改此文件,因为它是为我提供的。
#ifndef ALIEN_H
#define ALIEN_H
class Alien
{
public:
Alien();
Alien(int h, int w, char g);
void setHeight(int h);
void setWeight(int w);
void setGender(char g);
int getHeight();
int getWeight();
char getGender();
//operators: compare the aliens
bool operator==(const Alien& alien) const;
bool operator!=(const Alien& alien) const;
bool operator<=(const Alien& alien) const;
bool operator<(const Alien& alien) const;
bool operator>=(const Alien& alien) const;
bool operator>(const Alien& alien) const;
private:
int height; //inches
int weight; //pounds
char gender; //M or F
};
#endif
这是我的 Alien.cpp 文件。
#include "Alien.h"
#include <iostream>
using namespace std;
Alien::Alien()
{
height = 60;
weight = 100;
gender = 'M';
int statusPoints = 0;
}
Alien::Alien(int h, int w, char g)
{
height = h;
weight = w;
gender = g;
int statusPoints = 0;
}
void Alien::setHeight(int h)
{
height = h;
}
void Alien::setWeight(int w)
{
weight = w;
}
void Alien::setGender(char g)
{
gender = g;
}
int Alien::getHeight()
{
return height;
}
int Alien::getWeight()
{
return weight;
}
char Alien::getGender()
{
return gender;
}
bool Alien::operator==(const Alien& alien) const
{
return (height == alien.height && weight == alien.weight && gender == alien.gender);
}
bool Alien::operator!=(const Alien& alien) const
{
return (height != alien.height || weight != alien.weight || gender != alien.gender);
}
bool Alien::operator<=(const Alien& alien) const
{
Alien temp1;
Alien temp2;
int genderValue = 2;
if(gender == 'F')
{
genderValue = 3;
}
int statusPoints = 0;
if (statusPoints <= statusPoints)
{ return true; }
else { return false; }
}
如果我无法更改 .h 文件,或将 statusPoints 设为成员函数,我应该在哪里在 main 或重载运算符中创建 statusPoints 变量?另外...如何将 statusPoints var 分配给对象以进行比较?
任何帮助表示赞赏。谢谢。