【发布时间】:2023-04-01 12:58:01
【问题描述】:
我的 City 类包含以下私人数据:城市名称、城市的宽度、长度和高度。我必须制作动态数组,默认情况下由构造函数插入 - City(),当程序启动时。然后程序使用方法 output() 并打印插入的城市数组。
我应该使用冒泡排序来按城市的长度对城市进行排序。完成后,程序应该以越来越长的长度显示已排序的城市。
问题是我的数据是私密的(在公共场合一切都很好,但违反了封装原则!)所以我不能进行冒泡排序。
我尝试做另一个 double double Lengths[n] 类型的动态数组,其内容是第一个数组的长度。然后我进行排序,但程序只打印排序后的长度,这不是我的目标。
我应该打印按长度排序的城市名称。
代码:
class City{
private: char *name;
double width;
double length;
double height;
public:void Output();
City();
~City();
double GetLength()
{
return length;
}
double GetWidth(){ return width; }
double GetHeight(){ return height; }
char GetName(){ return *name; }
};
City::City()
{
char ime[20];
cout << "Name= ";
cin >> ime;
name = new char[strlen(ime) + 1];
for (int i = 0; i <=strlen(ime); i++)
name[i] = ime[i];
cout << "Width= ";
cin >> width;
cout << "Length= ";
cin >> length;
cout << "Height= ";
cin >> height;
}
void City::Output()
{
cout << "Name is: " << name << endl;
cout << " Width is: " << width <<" deg"<< endl;;
cout << " Length is: " << length << " deg"<<endl;
cout << " Height is: " << height <<" m"<<endl;
return;
}
City::~City()
{
cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}
int main()
{
//City town;
//town.Input();
//town.Output();
int n;
City *mA;
cout << "Input number of cities: " << endl;
cin >> n;
mA = new City[n];
for (int j = 0; j < n; j++)
{
mA[j].Output();
}
cout << "Cities from west to east, sorted by their length" << endl;
double *Lengths = new double[n];
for (int j = 0; j < n; j++)
{
Lengths[j] = mA[j].GetLength();
}
int k = 0;//counter
double max = Lengths[0];
for (int j = 1; j < n; j++)
{
if (Lengths[j - 1] >Lengths[j])
{
max = Lengths[j - 1];
Lengths[j - 1] = Lengths[j];
Lengths[j] = max;
}
}
for (int j = 0; j < n; j++)//cycle for output
{
mA[j].Output();
}
delete[]mA;
return 0;
}
【问题讨论】:
-
你违反了规则或0、3、5。添加一个最小的复制构造函数和
operator=。 What is The Rule of Three? 的可能重复项 -
我认为这只是为了尝试将冒泡排序作为一种学习练习。因为,在任何实际程序中,您应该只使用std::sort。