如何在C ++中使用聚合?如何在我的代码中实现它? [英] How do I use aggregation in C++? How do I implement it into my code?

查看:172
本文介绍了如何在C ++中使用聚合?如何在我的代码中实现它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要用来制作BikeWorkout课程的Workout课程。我不知道如何使用聚合,但我必须这样做。



This is the Workout class I want to use in order to make a "BikeWorkout" class. I am not sure how to use aggregation, but I have to do so.

class Workout { 
public: 
Workout ( ); 
Workout( int minutes, int heartRate ); 

int getLength( ) const; 
int getHeartRate( ) const; 
private: 
int my_Length; // this workout's length 
int my_HeartRate; // this workout's acheived heart-rate 
}; 



我也有.cpp文件。




I also have the .cpp file.

Workout::Workout () 
{ 
my_HeartRate = 165; 
my_Length = 30; 
} 

Workout::Workout( int len, int rate ) 
{ 
my_HeartRate = rate; 
my_Length = len; 
} 

int Workout::getLength() const 
{ 
return my_Length; 
} 

int Workout::getHeartRate() const 
{ 
return my_HeartRate; 
} 



如何开始我的BikeWorkout课程,如何使用聚合来调用我的父课程?谢谢您的时间。


How should I start my "BikeWorkout" class and how do I use aggregation to call my parent class? Thank you for your time.

推荐答案

聚合是类之间的一种'有'关系,其中父包含子,子可以独立于父存在。



在您的示例中,Workout将是子类,'BikeWorkout'类将包含指向'Workout'的指针。一个条件是Workout类的分配和取消分配不应该是BikeWorkout类的责任。它可以在其他地方创建并作为参数传递给BikeWorkout构造函数。



BikeWorkout类看起来像,



Aggregation is a kind of 'has a' relationship between classes where a parent contains a child and the child can exist independent of the parent.

In your example, Workout would be the child class and the 'BikeWorkout' class would contain a pointer to 'Workout'. One condition is that the allocation and de-allocation of the Workout class should not be the responsibility of BikeWorkout class. It may be created somewhere else and passed as an argument to the BikeWorkout constructor.

The BikeWorkout class would look like,

class BikeWorkout
{
public:
  BikeWorkout(Workout *workout)
    : mWorkout(workout)
  {
  }
private:
  Workout *mWorkout;
};


还要看一下这个 Wikipedia 页面:\"Composition over inheritance [ ^ ]。
Have also a look at this Wikipedia page: "Composition over inheritance"[^].


这篇关于如何在C ++中使用聚合?如何在我的代码中实现它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆