【问题标题】:Calling a method of a class within another class?在另一个类中调用一个类的方法?
【发布时间】:2013-02-15 14:07:54
【问题描述】:

我为链表中的一个节点定义了以下类:

template <class T>
struct ListItem
{
    T value;
    List<T> wordList; // <--------
    ListItem<T> *next;
    ListItem<T> *prev;

    ListItem(T theVal)
    {
       this->value = theVal;
       this->next = NULL;
       this->prev = NULL;
    }
};

上面的类包含另一个类,即List,它有自己的功能,其中一个是insertAtEnd。我创建了一个 ListItem,我想通过调用 insertAtEnd 来更改它的 wordList 组件的值。这样做的语法是什么?

这是列表类:

template <class T>
class List
{
    ListItem<T> *head;

public:

    // Constructor
    List();         //done

    //test function
    void displaylist();

    // Copy Constructor
    List(const List<T>& otherList);       //done

    // Destructor
    ~List();

    // Insertion Functions
    void insertAtHead(T item);        //done
    void insertAtTail(T item);        //done
    void insertAfter(T toInsert, T afterWhat);    //done
    void insertSorted(T item);                    //done

    // Lookup Functions
    ListItem<T> *getHead();                       //done
    ListItem<T> *getTail();                       //done
    ListItem<T> *searchFor(T item);               //done

    // Deletion Functions
    void deleteElement(T item);                   //done
    void deleteHead();
    void deleteTail();                            //done

    // Utility Functions
    int length();                                 //done
 };

下面是 insertAtTail 函数的实现。

template <class T>
void List<T>::insertAtTail(T item)
{
    ListItem<T>* a = new ListItem<T>(item);

    if(head==NULL)
    {
        head=a;
    }

    else
    {
        ListItem<T>* temp;
        temp=head;

        while(temp->next!=NULL)
        {
            temp=temp->next;
        }
        temp->next=a;
        a->prev=temp;
    }
}

【问题讨论】:

  • “我已经创建了一个 ListItem,我想通过调用 insertAtEnd 来更改它的 wordList 组件的值。” 或许可以展示一下到目前为止你所拥有的。你在这里只有一个 decl 和一个构造函数(以及一个缺失的初始化列表,应该为你的成员调用一个 copy-ctor)。
  • 你应该寻找一些关于 C++ 的教程。我什至不确定这是否是有效的 C++...首先尝试this
  • YourListItemVarName.wordList.insertAtEnd(..params...)

标签: c++ class syntax methods linked-list


【解决方案1】:

类似

wordList.insertAtEnd( .... arguments ....);

【讨论】:

    【解决方案2】:
    1. 我不知道您的确切用例,但我真的怀疑ListItem 应该有List
    2. 要使用wordList,只需执行this-&gt;wordList.insertAtEnd(........)this 在这里不是必须的)。

    【讨论】:

    • 我正在尝试创建的是一个函数,它接收一个包含数百个单词的文件,创建一个二维链表,每个节点包含另一个列表,其中包含以特定字母开头的所有单词.我要创建的函数声明如下: List Dictionary() 我被指示在 ListItem 结构中添加一个 List wordList 对象以继续执行此任务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    相关资源
    最近更新 更多