继承的基本概念

类与类之间的关系

这里写图片描述

#include<iostream>
using namespace std;

class A
{
public:
    void func() {
        cout << "funcA" << endl;
    }
    int a;
};

//类B拥有类A 的成员变量,B has A,即类B依赖于类A
class B
{
public:
    void funcB()
    {

    }
    A a;
};
//耦合度:高内聚 低耦合  ,程序员追求的最高境界设计模式

//类C的成员  需要类A的形参, 类C use A  ,耦合度低一些
class C
{
public:
    void funcC(A *a)
    {

    }

};

//类D继承A,即类D is A,耦合度高
class D :public A
{
public:
    void funcD()
    {
        cout << a << endl;//直接打印继承过来的a
    }

};

int main()
{

    cout << "" << endl;
    return 0;
}

继承的基本概念

这里写图片描述
这里写图片描述

#include<iostream>
#include<string> //string.h 是C语言的的字符串头文件
using namespace std;

class Student
{
public:
    Student(int id,string name)
    {
        this->id = id;
        this->name = name;
    }
    void printS()
    {
        cout << "id = " << this->id << ", name = " << this->name << endl;
    }

private:
    int id;
    string name;
};

//创建一个新的学生类,增加score功能
class Student2
{
public: 
    Student2(int id,string name,int score)
    {
        this->id = id;
        this->name = name;
        this->score = score;
    }

    void printS()
    {
        cout << "id = " << this->id << ", name = " << this->name << endl;
        cout << "score = " << this->score << endl;


    }
private:
    int id;
    string name;
    int score;//新add
};
//通过继承创建一个新的学生类
class Student3 :public Student 
{
public:
    Student3(int id,string name,int score) :Student(id,name)//通过父类来初始化
    {//在使用子类构造是,编译器会默认调用父类构造(不写就默认调用无参的父类构造)
        this->score = score;
    }
    void printS()
    {
        Student::printS();
        cout << "score = " << this->score << endl;
    }
private:
    int score;
};

int main()
{

    Student3 s3(1,"fyy",100);
    s3.printS();
    return 0;
}

总结:

耦合度:高内聚 低耦合 ,程序员追求的最高境界设计模式

在使用子类构造是,编译器会默认调用父类构造(不写就默认调用无参的父类构造)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值