我的班级PlaylistTrack
是Track
的子类(扩展该班级):
#include "track.h"
#include "album.h"
class PlaylistTrack : public Track //extends Track Class
{
private:
Album & newAlbum; //or
Album * newAlbum; //?
public:
PlaylistTrack(void);
~PlaylistTrack(void);
};
我希望我的语法正确。 你如何添加一个参考或指针指向某个轨道出现的专辑?
答案 0 :(得分:2)
我并不完全明白你在问什么,但听起来你想找到一个从PlaylistTrack获取专辑的方法。
class PlaylistTrack : public Track
{
public:
PlaylistTrack(Album * owner){ m_owner = owner; }
Album* getAlbum(){return m_owner;}
private:
Album* m_owner;
}
int main()
{
Album albumA;
PlaylistTrack newTrack(&albumA);
//Now the track knows what album it belongs to, but the album does not own the track yet.
std::cout << "New Track's Album: " << newTrack.getAlbum.getTitle() << std::endl;
//Now the album owns this track
albumA.addTrack(newTrack);
//The PlaylistTrack constructor could add itself to the album if you wanted to I think.
return 0;
}
答案 1 :(得分:0)
添加如下引用:
class PlaylistTrack : public Track //extends Track Class
{
private:
Album &album;
public:
PlaylistTrack(void);
~PlaylistTrack(void);
};
或像这样的指针:
class PlaylistTrack : public Track //extends Track Class
{
private:
Album *album;
public:
PlaylistTrack(void);
~PlaylistTrack(void);
};
当然,你可能想要修改你的构造函数,以便它需要一个专辑和曲目编号(或沿着那些行的东西),或者至少为专辑和曲目编号添加访问者。