当前位置:网站首页>C# 一周入门高级编程之《C#-继承》Day One
C# 一周入门高级编程之《C#-继承》Day One
2022-08-03 07:59:00 【太阳风暴】
一、继承是什么
继承是面向对象程序设计中最重要的概念之一。所谓继承,很明显,其实就是存在着两代或多代类,通过一种方式来将这继承关系的两代或者多代的功能给合成下来。这样就可以把功能组件化,同时也有利于重用代码和节省开发时间。
当创建一个类时,我们其实并不完全需要重新编写新的数据成员和成员函数,只需要设计一个新的类,继承了已有的类的成员即可。同时可以在该成员基础上进一步修改
二、基类和派生类
- 基类:就是初代的那个类
- 派生类:就是继承基类的类
就像动物 是 猫科动物、犬科动物的基类,而猫科动物又是老师的基类,存在着这样的衣襟带水的关系。
class Animal
{
public void setSpeed(int v)
{
speed = w;
}
public void setTime(int h)
{
time= h;
}
protected int speed;
protected int time;
}
// 派生类
class Cat: Animal
{
public int getLength()
{
return (speed * time);
}
}
三、基类初始化
基类的初始化有很多种方法,基类总是先被初始化然后派生类再初始化的。
派生类继承了基类的成员变量和成员方法。因此父类对象应在子类对象创建之前被创建。那我们可以在成员初始化列表中对父类的初始化。使用的关键字就是 base
class Animal
{
// 成员变量
protected double speed;
protected double time;
public Animal(double v, double t)
{
speed = v;
time = t;
}
public double GetLength()
{
return speed * time;
}
public void Display()
{
Console.WriteLine("速度: {0}", speed);
Console.WriteLine("时间: {0}", time);
Console.WriteLine("路程: {0}", GetLength());
}
}
class Cat: Animal
{
private double cost;
public Cat(double v, double t) : base(v, t)
{
}
public double GetCost()
{
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display()
{
base.Display();
Console.WriteLine("价格: {0}", GetCost());
}
}
四、使用接口的多继承
C#是不支持C++的那种多继承的方式的,但是还是给我们提供了一个 通过接口的方式继承,当然既然是接口继承得话,那继承接口的方法肯定是必须自己手写的。这其实也不算是多继承,我个人觉得。
代码如下:
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// 基类 PaintCost
public interface PaintCost
{
int getCost(int area);
}
// 派生类
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
//重写的接口函数,并没有真正继承到功能
public int getCost(int area)
{
return area * 70;
}
}
边栏推荐
猜你喜欢
随机推荐
面渣逆袭:MySQL六十六问,两万字+五十图详解
ceph简介
Docker启动mysql
pyspark---encode the suuid interval (based on the number of exposures and clicks)
Golang协程goroutine的调度与状态变迁分析
mysql备份时的快照原理
[ 漏洞复现篇 ] yapi 代码执行 getshell 漏洞复现详解
DSP-ADAU1452输出通道配置
0day_Topsec上网行为管理RCE
The use of the database table structure document generation tool screw
22-08-02 西安 尚医通(02)Vscode、ES6、nodejs、npm、Bable转码器
推荐系统-排序层-模型:Wide&Deep
Evaluate: A detailed introduction to the introduction of huggingface evaluation indicator module
ArcEngine (3) zoom in and zoom out through the MapControl control to achieve full-image roaming
解决移动端有纵向滚动条但是不能滚动的问题
五、《图解HTTP》报文首部和HTTP缓存
学习笔记:机器学习之逻辑回归
Roson的Qt之旅#105 QML Image引用大尺寸图片
DSP Trick:向量长度估算
解决GANs训练中模式崩塌/训练崩溃的十五个方法