程序设计(2)
4.(6分) class C_A {
public:
C_A(char value) {
data = value; m_count++;
cout << \cout << \ \} ~C_A()
{ cout <<\m_count--; } private: char data;
static int m_count; };
void Func();
int C_A::m_count = 0; int main()
{ C_A *pa = new C_A('a'); Func(); delete pa; Func();
return 0; }
void Func() { static C_A f('b'); C_A g('c'); }
第 6 页 共 14页
程序设计(2)
5.(6分) class CAutoMobile{ public:
CAutoMobile(const char *);
virtual ~CAutoMobile() {delete [] m_Model;} char * getModel() const { return m_Model;}
virtual double price() const = 0;
virtual void display() const {cout << getModel() << \’ price is undefined\ private:
char *m_Model; };
CAutoMobile::CAutoMobile(const char *model) { m_Model = new char[strlen(model) + 1];
strcpy(m_Model,model); }
class CCar:public CAutoMobile { public:
CCar(const char *model,double price = 0.0): CAutoMobile(model), m_Price(price) {}; virtual double price() const { return m_Price;} virtual void display() const
{ cout << \private:
int m_Price; };
void func1(const CAutoMobile &a ) { cout << \
a.display(); }
void func2(const CAutoMobile *a) { cout << \
a->display(); } int main()
{ CCar m(\
cout<<\
第 7 页 共 14页
程序设计(2)
m.display();
func1(m); func2(&m);
return 0; }
6. (4分) void func( int ) ; int main() { int i = 49; try{
while ( i > 0 )
{ func(i);
cout << i << endl; i = i / 2 - 1; } }
catch( int ex) {cout << ex << endl; }
return 0; }
void func(int num )
{ if ( ! (num % 3) ) throw 3; else if ( !(num % 4) ) throw 5; }
第 8 页 共 14页
程序设计(2)
7.(6分) class CDoor { public:
CDoor() { cout << \ up.\~CDoor() { cout << \};
class CWall { public:
CWall() { cout << \~CWall() { cout << \};
class CRoom { public:
CRoom():m_Door(),m_Wall() { cout << \~CRoom() { cout << \private:
CWall m_Wall; CDoor m_Door; }; int main() { CRoom room;
return 0; }
第 9 页 共 14页
程序设计(2)
三. 程序填空(30分)
1. 完成下列string类的定义。请填空。(6分)
class string{ char *str;
public: string(char *s)
{str = new char[strlen( s )+1]; strcpy(str,s) ;}
~string() { delete []str ;} string &operator=(string &s)
{if ( this==&s ) return *this; delete []str ;
str = new char[strlen(s.str)+1]; strcpy(str, s.str);
return *this ;}
};
2.(4分)请填空使得输出为:4+3I class complex {
int real; // 实部 int imag; // 虚部 public:
complex(int r=0, int i=0){ real=r ; imag=i ;} void show() { cout< int main() { complex c(3,3); ++c ; c.show() ; } 第 10 页 共 14页