p107.cpp
来自「《C++编程指南(续编)》的一些程序源代码」· C++ 代码 · 共 113 行
CPP
113 行
#include <fstream.h>
#include <strstrea.h>
#include <string.h>
char * makeCopy(char * pszS)
{
char * pszT=new char[strlen(pszS)+1];
strcpy(pszT,pszS);
return pszT;
}
class Student
{
public:
Student(char * pLN,char * pFN,
int nGrd,unsigned long ulId);
virtual ~Student();
void display(ostream& out)const;
protected:
char * pLName;
char * pFName;
int nGrade;
unsigned long ulID;
};
Student::Student(char * pLN,char * pFN,
int nGrd,unsigned long ulId)
{
pLName=makeCopy(pLN);
pFName=makeCopy(pFN);
nGrade=nGrd;
ulID=ulId;
}
Student::~Student()
{
delete pLName;
delete pFName;
}
void Student::display(ostream& out)const
{
static char szGrade[]="(Grade";
int nWidth=out.width();
out.width(0);
char cFill=out.fill();
int bLeft=(out.flags()&ios::left)!=0;
ostrstream local;
local<<pLName<<" , "
<<pFName<<" - "
<<ulID
<<szGrade
<<nGrade
<<")";
int nLength=local.pcount();
if(!bLeft)
{
int nI;
for(nI=nLength;nI<nWidth;nI++)
{
out<<cFill;
}
}
char * pszBuffer=local.str();
out.write(pszBuffer,nLength);
delete pszBuffer;
if(bLeft)
{
int nI;
for(nI=nLength;nI<nWidth;nI++)
{
out<<cFill;
}
}
}
ostream& operator<<(ostream& out,const Student& s)
{
s.display(out);
return out;
}
int main(int ,char **)
{
Student s1("Moore","John",-2,789123456L);
cout<<"Width set to 0: \n";
cout<<"["<<s1<<"]\n";
cout<<"\nWidth set to 80:\n";
cout.fill('*');
cout<<"[";
cout.width(80);
cout<<s1<<"]\n";
cout<<"\nWidth set to 80 ,ios : left bit set :\n";
cout.setf(ios::left);
cout<<"[";
cout.width(80);
cout<<s1<<"]\n";
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?