类的关系(C++实现)

1. 概述在面向对象的程序设计中,类共有六种关系,它们分别是Composition、Aggregation、Association、Dependency、Generalization和Realization。理解类的六大关系对于面向对象的程序设计非常重要,也是理解设计模式的前提。本文给出概念介绍并结合C++代码给出解释,由于作者本身能力有限,难免有不当甚至错误,欢迎指出。文中给出的实例的完整工程详见参考文献1。2. 组合(Composition)Composition是一种 "part-of"
摘要由CSDN通过智能技术生成

1. 概述

在面向对象的程序设计中,类共有六种关系,它们分别是Composition、Aggregation、Association、Dependency、Generalization和Realization。理解类的六大关系对于面向对象的程序设计非常重要,也是理解设计模式的前提。本文给出概念介绍并结合C++代码给出解释,由于作者本身能力有限,难免有不当甚至错误,欢迎指出。文中给出的实例的完整工程详见参考文献1。

2. 组合(Composition)

Composition是一种 "part-of" 的关系,如下图中的孕妇和婴儿。它是一种强所属关系,整体与部分往往具有相同的生命周期,整体的对象是在部分对象创建的同时或创建之后创建,在部分对象销毁的同时或之前销毁。

Composition.jpg

参考代码如下,讲的是游戏中每个生物体(Creature)都有自己的坐标位置,其中坐标位置用Point类表示,明显是一种"part-of"的关系。

#include <string>

struct Point
{
    Point() : x(0), y(0) { }

    void setPoint(const int x, const int y)
    {
        this->x = x;
        this->y = y;
    }
    int getPointX() const
    {
        return this->x;
    }
    int getPointY() const
    {
        return this->y;
    }

private:
    int x;
    int y;
};

struct Creature
{
    Creature() : name(""), location(location) { }

    void setCreature(const std::string& name, const Point& location)
    {
        this->name = name;
        this->location = location;
    }
    void move(int x, int y)
    {
        this->location.setPoint(x, y);
    }
    std::string getName() const
    {
        return this->name;
    }
    int getXLocation() const
    {
        return this->location.getPointX();
    }
    int getYLocation() const
    {
        return this->location.getPointY();
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值