自学内容网 自学内容网

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,Y
    cin >> 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,Y
    cin >> 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

得证。


原文地址:https://blog.csdn.net/2401_83411974/article/details/142502567

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!