【发布时间】:2019-02-24 05:16:17
【问题描述】:
目前我正在尝试使用多个类(每个类都有自己的 .cpp 和头 .h 文件)并使用主 .cpp 链接它们。 我想做一个临时的新视频对象指针,传入参数,插入到链表中,然后删除临时指针。之后,我需要打印列表中的每个单独节点。
目前有4个文件:main.cpp、vlist.cpp、vlist.h、video.cpp、video.h
我使用 vlist 作为一种方法来构造一个链表,该链表通过 vlist.cpp 文件中定义的插入函数传入视频对象指针中。 第一个问题是我不确定我是否正确地这样做了。 目前,为了能够在另一个类中传递视频对象,我所做的只是将 video.h 包含在vlist.h 文件。
第二个问题是我无法弄清楚如何正确访问每个节点中的各个视频对象属性,因为我的 getter 函数(在 video.h 中定义)不起作用。 他们似乎返回地址而不是值。但是,每当我尝试解决这个问题时,它都会告诉我不能像这样使用 getter 函数。
我的第三个也是最后一个问题是,在 vlist.cpp 中创建新节点时我无法传入 m_vid,但我可以传入 m_head 就好了。如果我不这样做,它将无法编译使用 myVid(在 vlist.h 中公开声明的视频对象指针)。
以下文件:
main.cpp
#include <iostream>
using namespace std;
#include "vlist.h"
#include "video.h"
int main()
{
//Create temporary video object pointer using Video * temp = new Video(arguments);
//Pass in the temp video pointer to the list and insert it with VList function
string firstLine, secondLine, thirdLine = "";
float fourthLine = 1.1;
int fifthLine = 2;
VList list;
Video * tempVid = new Video(firstLine, secondLine, thirdLine, fourthLine, fifthLine);
list.insert(tempVid);
delete tempVid;
list.print();
return 0;
}
视频.cpp
#include "video.h"
#include <iostream>
using namespace std;
Video::Video(string title, string URL, string comment, float length, int rating) {
vidTitle = title;
vidURL = URL;
vidComment = comment;
vidLength = length;
vidRating = rating;
}
void Video::print(Video *myVid) {
cout << myVid->getTitle() << endl;
}
视频.h
#ifndef VIDEO_H
#define VIDEO_H
#include <string>
#include <iostream>
using namespace std;
class Video
{
public:
Video(string title, string URL, string comment, float length, int rating);
int getRating() {
return vidRating;
}
float getLength() {
return vidLength;
}
string getTitle() {
return vidTitle;
}
string getURL() {
return vidURL;
}
string getComment() {
return vidComment;
}
void print(Video *myVid);
private:
string vidTitle, vidURL, vidComment, vidPreference;
float vidLength;
int vidRating;
};
#endif
vlist.cpp
#include <iostream>
using namespace std;
#include "vlist.h"
VList::VList() {
m_head = NULL;
}
VList::~VList() {
Node *ptr = m_head;
while (ptr != NULL) {
Node *temp;
temp = ptr;
ptr = ptr->m_next;
delete temp;
}
}
void VList::insert(Video *myVid) {
m_head = new Node(myVid, m_head);
}
void VList::print() {
Node *ptr = m_head;
while (ptr != NULL) {
cout << ptr->m_vid->getTitle();
ptr = ptr->m_next;
}
}
vlist.h
#ifndef VLIST_H
#define VLIST_H
#include "video.h"
class VList
{
public:
VList();
~VList();
void insert(Video *myVid);
void print();
Video *myVid;
private:
class Node
{
public:
Node(Video *myVid, Node *next) {
m_vid = myVid;
m_next = next;
}
Video *m_vid;
Node *m_next;
};
Node *m_head;
};
#endif
【问题讨论】:
标签: c++ class linked-list