《面向对象程序设计》第9次作业

  1. (填空题)
    阅读程序写结果

include <iostream.h>

class Student
{public:
    Student(int=0);    Student(Student &);   ~Student();   
private:
int age;
};
Student::Student(int age){this->age=age;cout<<"Constructor  "<age<<endl;}
Student::Student(Student &s){age=s.age+30;cout<<"Copy Constructor  "<age<<endl;}
Student::~Student(){cout<<"Destructor  "<<age<<endl;}
void test()
{Student s4(4); static Student s5(5); Student s6(6); Student s7(s4);
 cout<<"test  is called"<<endl;
}
Student s1(1);
void main()
{Student s2(2);
 static Student s3(3);
 Student s8(8);
 Student s9(s2);
  test();  
  cout<<"main end"<<endl;
}

//函数周期结束后要析构一次,但是里面的静态成员不析构,等main函数,开始先析构主函数里的其他对象,然后析构静态成员

Constructor 1
Constructor 2
Constructor 3
Constructor 8
Copy Constructor 32
Constructor 4
Constructor 5
Constructor 6
Copy Constructor 34
test is called
Destructor 34
Destructor 6
Destructor 4
main end
Destructor 32
Destructor 8
Destructor 2
Destructor 5
Destructor 3
Destructor 1

include "iostream.h"

class Shape
{protected:  double x,y;
public:
void setda(double i,double j){x=i;y=j;}
virtual void disparea() {cout<<"No area display";}
};

class Triangle:public Shape
{public:
void disparea()
{ cout<<"Triangle area";
cout<<xy0.5<<endl;
}
};

void main()
{ Shape *p,s;
Triangle t;
p=&t;
p->setda(2.0,5.0);
p->disparea();
p=&s;
p->setda(2.0,4.0);
p->disparea();
}
Triangle area5
No area display

include "iostream"

using namespace std; 
class Samp

{ public:

void Setij(int a,int b){i=a;j=b;}

~Samp(){cout<<"Destroying..."<<i<<endl;}

int GetMulti(){return i*j;}

protected:   int i,j;

};

int main()

{ Samp *p;

int i;

p=new Samp[5];

for(i=0;i<5;i++) p[i].Setij(i,i);

for(i=1;i<4;i++) cout<<"Multi["<<i<<"] is:"<<p[i].GetMulti()<<endl;

delete []p;
return 0;
}

//
//Multi[1] is:1
//Multi[2] is:4
//Multi[3] is:9
//
//Destroying...4
//Destroying...3
//Destroying...2
//Destroying...1
//Destroying...0

include "iostream.h"

class OBJ
{ public: OBJ(){cout<<"OBJ\n";}};
class VISUAL_BASE
{ public:
VISUAL_BASE(){cout<<"VISUAL_BASE\n";}
~VISUAL_BASE(){cout<<"DEL VISUAL_BASE\n";}
};
class BASE
{
public:
BASE(){cout<<"BASE\n";}
~BASE(){cout<<"Del BASE\n";}
};
class Child:virtual public VISUAL_BASE,public BASE
{ public:       Child(){}
protected:   OBJ obj;
};
void main()

C++ 构造函数调用的铁则(所有情况通用):
虚基类构造 → 普通基类构造 → 成员对象构造 → 派生类自身构造体

VISUAL_BASE
BASE
OBJ
Del BASE
DEL VISUAL_BASE

include “iostream.h”

void sub(int *s , int *t)

void main()
{ int a,b,p ,q;
a=100;b=200;
p=&a;q=&b;
sub(p,q);
cout<<p<<","<<q;
}

100,200

posted @ 2026-06-03 12:08  叶臧  阅读(7)  评论(0)    收藏  举报