关于c++自定义队列类和运算符重载Orz

想实现的功能是讲两个队列中不重复的部分加起来
这是主函数里的代码
Queue a, b;
a.push(1);
a.push(2);
a.push(3);
b.push(3);
b.push(4);
b.push(5);
Queue c, d;
cout << "a + b = ";
c = a + b;
cout<< c. back();
这是实现文件中的代码
template

Queue Queue::operator+(Queue obj)
{
int ahead = head;
Queue ans;
type temp;
while(!isEmpty())
{
ans.push(front());
pop();
}
head = ahead;
while(!obj.isEmpty())
{
temp = obj.front();
obj.pop();
while(!isEmpty())
{
if(temp == front())
{
break;
}
pop();
}
if(isEmpty())
ans.push(temp);
head = ahead;
}
head = ahead;
cout << ans.back() << endl;
return ans;
}

img


为什么在实现类中调用就没问题,而在主函数中调用,最后一个元素却变成了随机值呢。

是把a和b中不重复的元素合并到一个容器中吗?感觉逻辑不对啊,Queue自身的数据在第一个while循环中已经全部弹出了,在第二个while循环中本队列中已经没有数据了。代码修改如下:(如果不行的话,建议你把全部代码用代码段贴出来,帮你修改一下,只有这些代码没法调试)

template <typename type>
Queue Queue::operator+(Queue obj)
{
    Queue ans,tt;
    int flag = 0; //是否存在标记
    type temp,data;
    while(!obj.isEmpty())
    {
        temp = obj.front();
        obj.pop();
        //判断temp是否在本队列中
        flag = 0;
        while(!isEmpty())
        {
            data = front();
            pop(); //从本队列中弹出
            if(temp == data)
            {
                flag = 1;
                break;
            }
            tt.push(data); //先存到tt中
        }
        if(flag)
            ans.push(temp);
        //把tt中的数据存入本身
        while(!tt.empty())
        {
            push(tt.front());;
            tt.pop();
        }
    }
    return ans;
}

代码段贴代码:点击下面的图标,然后再粘贴代码即可。

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632