day5 c语言学习 C++

本文展示了如何使用C++定义一个Person类作为父类,然后创建一个Student子类,继承自Person。Person类包含name、age、height和weight属性,而Student类添加了额外的score属性。两者都有构造函数用于初始化成员变量,并重写了toString()方法来展示对象信息。
摘要由CSDN通过智能技术生成

定义两个类,一个人,一个学生。人为父类,学生为子类

#include <iostream>

class Person{
protected:
    std::string name;
    int age;
    int height;
    int weight;
public:
    Person(){
        this->name = "";
        this->age = 0;
        this->height = 0;
        this->weight = 0;
    }
    Person(std::string name, int age, int height, int weight):name(name),age(age),height(height),weight(weight){

    }
    std::string toString(){
        return "name: " + this->name + ",age: " + std::to_string(this->age) + ",height: " + \
                std::to_string(this->height) + ",weight: " + std::to_string(this->weight);
    }
};

class Student : public Person{
private:
    int score;
public:
    Student(){
        this->score = 0;
    }
    Student(std::string name, int age, int height, int weight, int score):Person(name,age,height,weight),score(score){

    }
    std::string toString(){
        return this->Person::toString() + ",score: " + std::to_string(this->score);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值