重载功能仅因返回类型而异

时间:2017-08-19 14:51:20

标签: c++ algorithm data-structures

我正在尝试制作一个程序来检测两个链表相交的位置。

class LinkedList 
{
    private:
        struct Node
        {
            int value;
            Node *next;
            Node(int v,Node *n);
            Node(int v);
        };
        Node *head;
        int list_size; 

        public:
            virtual int size();
            virtual bool isEmpty();

            virtual int findLength();

            virtual LinkedList *findIntersection( Node *head, Node *head2);
        // Other linked list methods. 
};

LinkedList:: Node:: Node(int v,Node *n)
{
    value = v;
    next = n; 
}

LinkedList:: Node:: Node(int v) 
{
    value = v;
    next = nullptr; 
}

LinkedList:: Node *LinkedList:: findIntersection( Node *head, Node *head2) 
{
    int l1 = 0;
    int l2 = 0;
    Node *tempHead = head;
    Node *tempHead2 = head2;
    while (tempHead != nullptr)
    {
        l1++;
        tempHead = tempHead-> next;
    }
    while (tempHead2 != nullptr)
    {
        l2++;
        tempHead2 = tempHead2-> next;
    }
    int diff;
    if (l1 < 12)
    {
        Node *temp = head;
        head = head2;
        head2 = temp;
        diff = l2 - l1;
    }
    else
    {
        diff = l1 - l2;
    }
    for (; diff > 0; diff--)
    {
        head = head-> next;
    }
    while (head != head2)
    {
        head = head-> next;
        head2 = head2-> next;
    }
    return head; 
}

我在main()中调用上述函数,如下所示:

int main()
{
    LinkedList* ll = new LinkedList();  LinkedList* l2, l3;
    l3 = ll->findIntersection( ll, l2);
    cout<<"\nIntersection point is: ";  l3 -> print();
    return 0;
}

我收到以下错误:

error C2556: 'LinkedList::Node *LinkedList::findIntersection(LinkedList::Node *,LinkedList::Node *)':
  overloaded function differs only by return type from 
  'LinkedList *LinkedList::findIntersection(LinkedList::Node *,LinkedList::Node *)'
error C2371: 'LinkedList::findIntersection': redefinition; different basic types

如何删除此错误?

1 个答案:

答案 0 :(得分:1)

问题是你的findIntersection函数声明与定义不同。

宣言是

virtual LinkedList *findIntersection( Node *head, Node *head2);

定义是

LinkedList:: Node *LinkedList:: findIntersection( Node *head, Node *head2) 

正如您在比较它们时可以轻松看到的那样,返回类型是不同的。其中一个必须是拼写错误。