继承经典案例

一、正方形边长

1、有成员属性width(长,int),成员属性height(宽,int)。

2、将width和height设置为私有属性,并提供公开的get,set函数。

3、有合理的构造函数,构造函数必须初始化height和width。

自定义类表示正方形(Square)继承自矩形(Rectangle)

 要求:

1、改写父类的set函数,保证当正方形修改边长时长和宽都会改变。

2、有合理的构造函数,构造函数必须初始化Rectangle

代码示例:

#include <iostream>
#include <string>
using namespace std;

class Rectangle
{
    private:
        int width;
        int height;
    public:
        Rectangle():width(),height(){}
        Rectangle(int width,int height):width(width),height(height){}
        void setWidth(int width)
        {
            this->width = width;
        }
        int getWidth()const
        {
            return width;
        }
        void setHeight(int height)
        {
            this->height = height;
        }
        int getHeight()const
        {
            return height;
        }
};

class Square:public Rectangle{
    public:
        Square():Rectangle(){};
        Square(int size):Rectangle{size,size}{}
        void setWidth(int width)
        {
            Rectangle::setWidth(width);
            Rectangle::setHeight(width);
        }
        void setHeight(int height)
        {
            Rectangle::setHeight(height);
            Rectangle::setWidth(height);
        }
};

int main()
{
    Square s1(20);
    s1.setHeight(10);
    cout<<"正方形的边长:"<<s1.getHeight()<<endl;
    cout<<"正方形的边长:"<<s1.getWidth()<<endl;
    return 0;
}

 注:int getHeight()const输出函数加const常量,表示该成员函数是一个常量成员函数,即在该函数中不能修改对象的成员变量。保证输出参数的稳定性。

运行结果:

正方形的边长:10
正方形的边长:10

二、学生信息

自定义类表示人(Person)。

要求:

1、有成员属性name(姓名,string),age(年龄,int)。

2、将name,age设为受保护属性。

3、有合理的构造函数,构造函数必须初始化name和age。

自定义类表示学生(Student)继承自人(Peron)。

要求:

1、添加属性score(成绩,int)。

2、将score设置为私有属性,并提供公开的get,set函数。

3、有公开的成员函数describe,可以用string描述学生的姓名,年龄和成绩。

建议describe的函数原型:string Student::describe()const;

4、有合理的构造函数,构造函数必须初始化Person和score

代码示例:

#include <iostream>
#include <string>
using namespace std;

class Person{
    protected:
        string name;
        int age;
    public:
        Person():name(),age(){}
        Person(string name,int age):name{name},age{age}{}
};

class Student:public Person
{
    private:
        int score;
    public:
        Student():Person(),score(){}
        Student(string name,int age,int score):Person{name,age},score{score}{}
        int getScore()const
        {
            return score;
        }
        void setScore()
        {
            this->score = score;
        }
        string describe()const
        {
            return "学生姓名:"+name+"学生年龄:"+to_string(age)+"学生成绩:"+to_string(score);
        }
};

int main()
{
    Student Student("gaoyinjie",27,102);
    cout<<Student.describe()<<endl;
    return 0;
}

运行结果: 

学生姓名:gaoyinjie学生年龄:27学生成绩:102

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值