欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > C++_CH19_继承

C++_CH19_继承

2025/2/25 9:22:06 来源:https://blog.csdn.net/2401_83411974/article/details/142502567  浏览:    关键词:C++_CH19_继承

C++_CH19_继承

面向对象编程是一个巨大范式,而继承则是一个基本的方面。继承允许类有一个相互关联的层次结构。即允许一些子类有一些公共的功能(基类),又有自己的部分。可以帮助我们减少代码的重复。

1、继承怎么写

在游戏当中,我们需要一个实体的类,来标记它的位置,和进行移动。

#include <iostream>
using namespace std;class Entity
{
public:float X,Y;void move(float xa,float ya){X += xa;Y += ya;}
};

在这个类的基础上,我们写玩家的类,玩家player实际上也是实体的一种,所以实体是玩家的父类,玩家是实体的子类。
那么怎么写呢?

class player : public Entity
#include <iostream>
using namespace std;class Entity
{
public:float X,Y;void move(float xa,float ya){X += xa;Y += ya;}
};class player : public Entity
{
public:char* name;int age;void Print(name,age){cout<< "玩家名: "<< name <<endl;cout<< "年龄: "<<age<<endl;} 
};

这个类表明,player类不仅有Entity类的所有东西,而且还有自己特有的,Print这个method和年龄,姓名的信息。只要是父类的public的部分,子类都相当于有。

#include <iostream>
#include <cstring> // 包含头文件以使用strlen和strcpy
using namespace std;class Entity {
public:float X, Y;void move(float xa, float ya) {X += xa;Y += ya;}
};class player : public Entity {
public:char name[100]; int age;void Print() {cout << "玩家名: " << name << endl;cout << "年龄: " << age << endl;}void Position() { cout << X << " " << Y << endl;}
};int main() {player wang; // 创建叫wang的玩家wang.X = 10.0f;wang.Y = 9.0f; // 可以访问X,Ycin >> wang.name; // 输入姓名cin >> wang.age; // 输入年龄wang.Print(); // 打印出来wang.move(2.0f, 3.0f); // 移动角色wang.Position(); // 打印角色位置cin.get(); // 等待用户输入return 0;
}

2 证明Entity和player元素互通

player这里只有一个char类型,则他的类型大小应该是400,但是如果player和Entity互通,则player应该是4+4+4+100 = 112。用sizeof(player)可以证明这一点。

#include <iostream>
#include <cstring> // 包含头文件以使用strlen和strcpy
using namespace std;class Entity {
public:float X, Y;void move(float xa, float ya) {X += xa;Y += ya;}
};class player : public Entity {
public:char name[100]; int age;void Print() {cout << "玩家名: " << name << endl;cout << "年龄: " << age << endl;}void Position() { cout << X << " " << Y << endl;}
};int main() {player wang; // 创建叫wang的玩家wang.X = 10.0f;wang.Y = 9.0f; // 可以访问X,Ycin >> wang.name; // 输入姓名cin >> wang.age; // 输入年龄wang.Print(); // 打印出来wang.move(2.0f, 3.0f); // 移动角色wang.Position(); // 打印角色位置cin.get(); // 等待用户输入std::cout<<sizeof(player);return 0;
}

output:

112

得证。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词