#include<iostream>
#include<cstdio>
using namespace std;
class Base
{
private:
int data1;
public:
static int object_Base;//静态成员,用来记录创建的对象个数
Base(int num);//构造函数
friend void Print(Base b);//友元函数
~Base(){};//析构函数;
};
int Base::object_Base=0;
Base::Base(int num):data1(num)
{
object_Base++;
}
void Print(Base b)
{
printf("%d\n",b.data1);
}
class Derived:public Base
{
private:
int data2;
public:
static int object_Derived;
Derived(int num1,int num2);
friend void Print(Derived d);
};
int Derived::object_Derived=0;
Derived::Derived(int num1,int num2):Base(num1)
{
object_Derived++;
data2=num2;
}
void Print(Derived d)
{
printf("%d\n",d.data2);
}
int main()
{
Base base(1);
Derived derived(3,2);
base=derived;//派生类的对象可以赋值给基类的对象,反之不成立
Print(base);
Base &base2=derived;//派生类对象可以初始化基类引用
Print(base2);
Base *base3=&derived;//派生类对象的地址可以赋值给基类的指针
Print(*base3);
cout<<"the total object is:"<<Base::object_Base+Derived::object_Derived<<endl;
return 0;
}
创建派生类对象时相应创建一个基类对象
#include<iostream>
#include<cstdio>
using namespace std;
class Shape
{
private:
int length,breadth;
public:
static int object_shape;
static void print_shape();
Shape();
void Set(int l,int b);
int Get();
friend void Print(Shape s);
};
int Shape::object_shape=0;
void Shape::print_shape()
{
printf("%d\n",Shape::object_shape);
}
Shape::Shape()
{
object_shape++;
}
void Shape::Set(int l,int b)
{
length=l;
breadth=b;
}
int Shape::Get()
{
return length*breadth;
}
void Print(Shape s)
{
printf("%d\n",s.Get());
}
class Rectangle:public Shape
{
private:
int height;
public:
static int object_rectangle;
static void print();
Rectangle();
void Set(int l,int b,int h);
int Get();
friend void Print(Rectangle r);
};
int Rectangle::object_rectangle=0;
void Rectangle::print()
{
printf("%d\n",object_rectangle);
}
Rectangle::Rectangle()
{
object_rectangle++;
}
void Rectangle::Set(int l,int b,int h)
{
Shape::Set(l,b);
height=h;
}
int Rectangle::Get()
{
return Shape::Get()*height;
}
void Print(Rectangle r)
{
printf("%d\n",r.Get());
}
int main()
{
Shape s;
Rectangle r;
r.Set(1,2,3);
s=r;//共有继承,可以将派生类赋值给基类
Print(s);
Print(r);
Shape::print_shape();//输出1,创建shape的派生类对象相应创建一个基类对象;
Rectangle::print();
return 0;
}