5.1
#include <iostream>
#include <complex>
using namespace std;
class Base
{
public:
Base() {cout<<"Base-ctor"<<endl;}
~Base() {cout<<"Base-dtor"<<endl;}
virtual void f(int){cout<<"Base::f(int)"<<endl;}
virtual void f(double){cout<<"Base::f(double)"<<endl;}
virtual void g(int i=10){cout<<"Base::g()"<<i<<endl;}
};
class Derived : public Base
{
public:
Derived() {cout<<"Derived-ctor" <<endl;}
~Derived(){cout<<"Derived-dtor"<<endl;}
void f(complex<double>) {
cout<<"Derived::f(complex)"<<endl;
}
void g(int i=20){
cout<<"Derived::g()"<<i<<endl;
}
};
int main()
{
cout<<sizeof(Base)<<endl;
cout<<sizeof(Derived)<<endl;
Base b;
Derived d;
Base *pb=new Derived;
b.f(1.0);
d.f(1.0);
pb->f(1.0);
b.g();
d.g();
pb->g();
delete pb;
return 0;
}
5.2
#include <iostream>
using namespace std;
class Base
{
public:
Base():data(count)
{
cout<<"Base-ctor"<<endl;
++count;
}
~Base()
{
cout<<"Base-dtor"<<endl;
--count;
}
static int count;
int data;
};
int Base::count;
class Derived : public Base
{
public:
Derived():data(count),data1(data)
{
cout<<"Derived-ctor"<<endl;
++count;
}
~Derived()
{
cout<<"Derived-dtor"<<endl;
--count;
}
static int count;
int data1;
int data;
};
int Derived::count=10;
int main()
{
cout<<sizeof(Base)<<endl;
cout<<sizeof(Derived)<<endl;
Base* pb = new Derived[3];
cout<<pb[2].data<<endl;
cout<<((static_cast<Derived*>(pb))+2)->data1<<endl;
delete[] pb;
cout<<Base::count<<endl;
cout<<Derived::count<<endl;
return 0;
}
5.3
#include <iostream>
#include <new>
#include <assert.h>
using namespace std;
class Abstract
{
public:
Abstract()
{
cout << "in Abstract()"<<endl;
}
virtual void f() = 0;
};
class Subclass:public Abstract{
public:
Subclass(){
cout<<"in Subclass()"<<endl;
}
void f(){
cout<<"Subclass::f()"<<endl;
}
};
int main()
{
Abstract *p = new Subclass;
p->f();
delete p;
return 0;
}
5.4
#include<iostream>
#include<cmath>
#define PI 3.14
using namespace std;
class shape
{
public:
virtual float area()=0;
};
class triangle:public shape{
public:
triangle(float A,float B,float C){
a=A;
b=B;
c=C;
}
float area(){
p=(a+b+c)/2.0;
s=sqrt(p*(p-a)*(p-b)*(p-c));
return s;
}
private:
float a,b,c,p,s;
};
class circles:public shape{
public:
circles(float R){
r=R;
}
float area(){
s=PI*r*r;
return s;
}
private:
float r,s;
};
int main()
{
shape *p;
triangle t(3,4,5);
circles c(10);
p=&t;
cout<<"triangle area:"<<p->area()<<endl;
p=&c;
cout<<"circles area:"<<p->area()<<endl;
}
5.5
#include<iostream>
using namespace std;
class Base{
public:
virtual void abstractMethod() = 0;
};
class Derived:public Base{
public:
void abstractMethod(){
cout<<"Derived::abstractMethod is called"<<endl;
}
};
int main()
{
Base* pBase = new Derived;
pBase->abstractMethod();
delete pBase;
return 0;
}