急!这个类编译不报错,执行却出了大问题。
以下代码中我定义了一个Manager类,是继承的Employee类的。然后动态申请了一个Manager类的数组。可是在准备将数组成员按工资的多少从新排序时,编译没报错,执行却出了问题。不能输出排序结果,而且弹出C++ 2005 出错将关闭的窗口。相关代码如下!希望大家能在不妥之错指正。
#include<string>
#include<iostream>
#include<cassert>
using namespace std;
class Employee
{protected:
string name;
int ID;
public:
Employee(char* a, int b)
:name(a),ID(b)
{}
Employee (const Employee& s)
{
assert(this!=& s);
name=s.name;
ID=s.ID;}
Employee& operator=(const Employee& rhs)
{
assert(this!=&rhs);
name=rhs.name;
ID=rhs.ID;
return *this;
}
void print()
{ cout<<name<<ID<<endl;}
};
class Manager:public Employee
{
private:
int sal;
public:
Manager(char*a=" ", int b =0, int c =0)
:Employee(a,b),
sal(c)
{}
Manager(const Manager& s)
:Employee(s)
{ sal=s.sal;}
Manager& operator=(const Manager& rhs)
{ ID=rhs.ID;
name=rhs.name ;
sal=rhs.sal;
return *this;}
void print() {cout<<name<<'\t'<<ID<<"号"<<sal<<"圆"<<endl;}
void SetManager(){ cin>>name ; cin>>ID; cin>>sal;}
friend int showsal( const Manager& s)
{ return s.sal ;}
friend string showname (const Manager& t)
{ return t.name ;}
};
int main ()
{ double p=0; int sum=0;
Manager t;
Manager *s= new Manager[5];
assert(s !=NULL);
cout<<"please enter 5 elements"<<endl;
for(int i=0;i!=5;++i)
{s[i].SetManager ();}
cout<<"finished"<<endl;
for(int i=0;i!=5;++i)
{s[i].print();}
for (int i=0;i!=5;++i)
{
sum=sum+showsal(s[i]);}
p=sum/5;
cout<<"平均工资为:"<<p<< "圆"<<endl;
cout<<"工资比较高的人为:"<<endl;
for(int i=0;i!=5;++i)
{
if( showsal(s[i])>=p)
cout<<showname(s[i])<<endl;
}
for( int i=0;i!=5;++i)
for(int j=i+1;i!=5;++i)
if(showsal(s[i])>showsal(s[j])) //这里是排序代码
{t=s[i];
s[i]=s[j];
s[j]=t;}
for(int i=0;i!=5;++i) // 排序后从新输出数组成员
{s[i].print();}
delete []s;
}