资源描述
东南大学09级C++(下)上机试卷B-答案
一、改错题(50分)本题共10个错误,每个错误5分
#include <iostream>
#include <cstring>
using namespace std;
class student
{
char *pName;
public:
student();
student(char *pname);
student(student &s);
~student();
student & operator=(student &s);
void print();
};
student::student() //去掉void
{
cout<<"Constructor";
pName=NULL;
cout<<"缺省"<<endl;
}
student::student ( char *pname )
{
cout<<"Constructor";
pName = new char[strlen(pname)];
if ( pName ) strcpy ( pName, pname); //pName与pname互换位置
cout<<pName<<endl;
}
student::student(student &s) //改为student &s
{
cout<<"Copy Constructor";
if(s.pName)
{
int len = strlen( s.pName );
pName = new char[len+1]; //len改为len+1
if ( pName ) strcpy (pName, s.pName);
cout<<pName<<endl;
}
else pName=NULL;
}
student::~student()
{
cout<<"Destructor";
if ( pName ) cout<<pName<<endl;
delete pName; //改为delete pName;
}
student & student::operator = ( student &s )
{
cout<<"Copy Assign operator";
delete[] pName;
if ( s.pName )
{
pName = new char[strlen(s.pName)+1];
if ( pName ) strcpy ( pName, s.pName );
cout<<pName<<endl;
}
else pName=NULL;
return *this; //改为return *this;
}
void student::print( ) //改为void student::print( )
{
if (pName = NULL ) cout << "NULL" << endl;
else cout << pName << endl;
}
void main(void)
{
student s1("范英明"),s2("沈俊");
student *s3 = new student;
*s3 = s1; //改为*s3 = s1;
s1.print();
s2.print();
s3->print(); //改为s3->print();
delete s3;
return; //去掉0
}
二、编程题(50分)每段代码10分,共50分。红字为要求设计的部分。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class goods;
ostream& operator<<(ostream &os, goods &a);
istream& operator>>(istream &is, goods &a);
class goods
{
string Name; //名称
int Amount; //数量
float Price; //单价
public:
goods ();
~ goods (); //析构函数,将数据保存到文件中
bool IsEmpty(){ return Name==""; };
friend ostream& operator<<(ostream &os, goods &a); //用于直接输出数组对象
friend istream& operator>>(istream &is, goods &a);
};
goods:: goods ()
{
ifstream file("goodinfo.data");
if ( file ) //文件打开成功
{
file >> *this;
file.close();
}
else
{
Name = "";
Amount = 0;
Price = 0;
}
}
goods::~ goods ()
{
ofstream file("goodinfo.data");
file << *this;
file.close();
}
ostream& operator << (ostream &os, goods &a)
{
os << a.Name << endl;
os << a.Amount << endl;
os << a.Price << endl;
return os;
}
istream& operator >> (istream &is, goods &a)
{
if ( is == cin )
{
cout << "请输入你的以下信息:" << endl;
cout << "名称:";
is >> a.Name;
cout << "数量:";
is >> a.Amount;
cout << "单价:";
is >> a.Price;
}
else
{
is >> a.Name;
is >> a.Amount;
is >> a.Price;
}
return is;
}
void main()
{
goods g;
if ( g.IsEmpty() ) cin >> g;
cout << endl;
cout << "显示商品信息:" << endl;
cout << g;
}
展开阅读全文