C++正在考试 在线等答案 急!!!!! 帮忙各位

二、 编程题
写一个C++程序,声明一个sailboat(帆船类);其私有成员包括制造商、船名、长度、宽度和吃水深度。其set成员函数给所有数据成员进行赋值。Writeinfo函数将船所有数据打印到屏幕上,并重载“〉”操作符用于船对象进行比较,如果一艘船船体较长,则较大。如果长度相同,则宽度大的船较大。
要求:在mian程序要建立有5个元素的sailboat数组。把 sailboat数组5个元素数据显示出来,并把船从小到大的排序结果打印到屏幕上。

#include<iostream>
#include<string>
using namespace std;
class sailboat
{
private:
string creater;//制造商
string name;//船名
double lenth;
double width;
double depth;
public:
void set()
{
cout<<"输入制造商:";
cin>>creater;
cout<<"输入船名:";
cin>>name;
cout<<"输入长度:";
cin>>lenth;
cout<<"输入宽度:";
cin>>width;
cout<<"输入吃水深度:";
cin>>depth;
cout<<endl;
}
void Writeinfo()
{
cout<<"制造商:\t"<<creater<<endl;
cout<<"船名:\t"<<name<<endl;
cout<<"长度:\t"<<lenth<<endl;
cout<<"宽度:\t"<<width<<endl;
cout<<"吃水深度:"<<depth<<endl;
cout<<endl;
}
int operator >(sailboat &s)
{
if(lenth==s.lenth)
return width>s.width;
else return lenth>s.lenth;
}
};
int main()
{
sailboat s[5];
int i,j;
for(i=0;i<5;i++)
s[i].set();
cout<<"排序前:------------------"<<endl;
for(i=0;i<5;i++)
s[i].Writeinfo();

sailboat temp;
for(i=1;i<5;i++)
for(j=0;j<5-i;j++)
if(s[j]>s[j+1])
{
temp=s[j];
s[j]=s[i+1];
s[j+1]=temp;
}
cout<<"排序后:-------------------"<<endl;
for(i=0;i<5;i++)
s[i].Writeinfo();
return 0;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2008-12-24
class sailboat
{
public:
void Set(char* szName ,int iLen , char* szCreateName ,int iLen2 , int iWidth , int iHeight ,int iDeep )
{
memncpy( m_szName , szName , iLen);
memncpy( m_szCreateName , szCreateName , iLen2);
m_iWidth = iWidth;
m_iDeep = iDeep;
m_iHeight = iHeight;
}

void WriteInfo()
{
printf("%s , %s , %d , %d , %d " , m_szName ,m_szCreateName ,m_iWidth , m_iHeight , m_iDeep);
}

bool operator> ( const sailboat& s)
{
if ( m_iHeight > s.m_iHeight )
return true;
else if ( m_iHeight == s.m_iHeight )
{
if ( m_iWidth > s.m_iWidth )
return true;
else
return false;
}
else
return false ;
}
private:
char m_szName[20];
char m_szCreateName[20];
int m_iHeight;
int m_iWidth ;
int m_iDeep;
};
第2个回答  2008-12-24
#include <iostream>
#include <cstdlib>
using namespace std;

const int NAME_LENGTH=20;

class sailBoat
{
public:

void set()
{
scanf("%s%s%d%d",m_name,m_creator,&m_lenth,&m_width,&m_depth);
}

void Writeinfo()
{
printf("%s , %s , %d , %d , %d " , m_name ,m_creator , m_lenth,m_width , m_depth);
}

bool operator> ( const sailBoat& s)
{
if ( m_lenth> s.m_lenth)
return true;
else if ( m_lenth== s.m_lenth)
{
if ( m_width > s.m_width )
return true;
}
return false ;
}

private:
char m_name[NAME_LENGTH+1];
char m_creator[NAME_LENGTH+1];
int m_lenth;
int m_width ;
int m_depth;
};

int cmp(const void *a,const void *b)
{
return *(sailBoat*)a>*(sailBoat*)b;
}

int main()
{
sailBoat s[5];
int i;

for(i=0;i<5;i++)
s[i].set();

qsort(s,5,sizeof(sailBoat),cmp);

for(i=0;i<5;i++)
s[i].Writeinfo();

return 0;
}
相似回答
大家正在搜