2018.6.4(public继承的赋值兼容规则)

https://www.icourse163.org/learn/PKU-1002029030?tid=1002785058#/learn/content?type=detail&id=1003870398&cid=1004682699&replay=true

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值