You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++队列插入10个姓名操作出现operator=歧义报错求助

C++队列代码歧义报错修复

错误根因

  • 你实例化了元素类型为std::string的队列模板,但代码内两处存在给数组元素直接赋值整数0的操作:
    1. 构造函数内arr[i] = 0;
    2. deletion方法内arr[front] = 0;
  • std::string的赋值运算符没有直接适配int类型的重载,编译器无法判断0需要转换为char还是const char*类型,因此触发operator = is ambiguous歧义报错。
  • 同时原代码缺失必要头文件#include <iostream>、#include <string>,也没有声明std命名空间的使用,编译也会报错。

修复方案

将两处赋值0的代码替换为泛型默认构造值t(),适配所有模板支持的类型:int类型默认构造为0,string类型默认构造为空字符串,完全符合你需要的清空效果。如果需要string类型删除后显示字符0,可以替换为t("0")即可。

修复后完整可运行代码

#include <iostream>
#include <string>
using namespace std;

template<class t>
class Queue
{
private:
    int front;
    int rear;
    t arr[10];

public:
    Queue()
    {
        front = -1;
        rear = -1;
        for (int i = 0; i < 10; i++) 
        {
            arr[i] = t(); // 替换为泛型默认值
        }
    }
    int isEmpty()
    {
        return (front == -1 && rear == -1) ? 1 : 0;
    }
    int isFull() 
    {
        return (rear == 9) ? 1 : 0;
    }
    void insertion(t value)
    {
        if (isFull()==1)
        {
            cout << "Cant be inserted ,Queue full" << endl;
        }
        else if (isEmpty()==1) 
        {
            front = 0;
            rear = 0;
            arr[rear] = value;
        }
        else 
        {
            rear++;
            arr[rear] = value;
        }
    }

    t deletion()
    {
        t x ;
        if (isEmpty()==1) 
        {
            cout << "Cant be deleted ,Queue is Empty" << endl;
            return x;
        }
        else if (rear == front) 
        {
            x = arr[rear];
            rear = -1;
            front = -1;
            arr[rear+1] = t(); // 替换为泛型默认值
            return x;
        }
        else 
        {
            cout << "front value: " << front << endl;
            x = arr[front];
            arr[front] = t(); // 替换为泛型默认值
            front++;
            return x;
        }
    }

    int count()
    {
        if(isEmpty()) return 0;
        return (rear - front + 1);
    }

    void display()
    {
        cout << "All values in the Queue are - " << endl;
        for (int i = 0; i < 10; i++) 
        {
            cout << arr[i] << "  ";
        }
        cout << endl;
    }
};

int main() {
    Queue <string> q1;
    string name;
    cout << "Enter 10 names:" << endl;
    for (int i = 0; i < 10; i++)
    {
        cin >> name;
        q1.insertion(name);
    }
    q1.display(); // 展示插入后的全部内容
    for (int i = 0; i < 10; i++)
    {
        q1.deletion();
    }
    q1.display(); // 展示删除后的全部内容,输出全空/全0
    return 0;
}

功能验证

修复后代码运行流程:

  1. 输入10个姓名后调用display会输出所有输入的姓名
  2. 全部删除后调用display会输出10个空字符串(如果实例化为Queue<int>则输出10个0),符合需求。

内容的提问来源于stack exchange,提问作者codeplayer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:06:03