C++中实现[]重载报错?

在visual_studio中想做一个[]重载的小练习,

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

struct Person
{
    double salary;
    char *name;
};

class SalaryManage
{
private:
    Person *employ;
    int max;
    int n;
public:
    SalaryManage(int Max = 0)
        :max(Max),n(0),employ(new Person[max])
    {
    }

    double  &operator[](char *Name) 
    {
        Person *p;
        for (p = employ;p < employ + n;p++)
            if (strcmp(p->name, Name) == 0)
                return p->salary;
        p = employ + n++;
        p->name = new char[strlen(Name) + 1];
        strcpy(p->name, Name);
        p->salary = 0;
        return p->salary;
    }

    void display()
    {
        for (int i = 0;i < n;i++)
            cout << employ[i].name << "  " << employ[i].salary << endl;
    }
    ~SalaryManage()
    {
        delete[] employ;
    }
};

int main()
{
    SalaryManage s(3);
    s["张三"]  = 2188.88;
    s["里斯"] = 1234.65;
    s["王五"] = 3200.98;
    cout << "张三\t" << s["张三"] << endl;
    cout << "里斯\t" << s["里斯"] << endl;
    cout << "王五\t" << s["王五"] << endl;

    s.display();
}

可是主函数部分显示
image.png

作为C++新手,请大佬们帮忙指点一二

阅读 449
avatarAI BotBETA

这个错误是由于您在 SalaryManage 类的 operator[] 中没有正确地处理数组越界的情况。当您没有找到与 Name 匹配的名称时,您创建了一个新的 Person 对象并将其添加到数组的末尾,但您没有更新 n 的值,这导致在尝试访问不存在的数组索引时出现错误。

为了解决这个问题,您应该在添加新 Person 对象后将 n 的值增加 1。这样,您就可以正确地访问新添加的元素。此外,您应该在 display 函数中更新数组的长度。以下是更正后的代码:

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

struct Person
{
 double salary;
 char *name;
};

class SalaryManage
{
private:
 Person *employ;
 int max;
 int n;
public:
 SalaryManage(int Max = 0)
 :max(Max),n(0),employ(new Person[max])
 {
 }

 double& operator[](const char* Name) 
 {
 Person *p = nullptr;
 for (int i = 0; i < n; i++)
 {
 if (strcmp(employ[i].name, Name) == 0)
 {
 p = &employ[i];
 break;
 }
 }
 if (p == nullptr)
 {
 p = &employ[n++];
 p->name = new char[strlen(Name) + 1];
 strcpy(p->name, Name);
 p->salary = 0;
 }
 return p->salary;
 }

 void display() const
 {
 for (int i = 0; i < n; i++)
 cout << employ[i].name << "  " << employ[i].salary << endl;
 }
 ~SalaryManage()
 {
 delete[] employ;
 }
};

int main()
{
 SalaryManage s(3);
 s["张三"]  = 2188.88;
 s["里斯"] = 1234.65;
 s["王五"] = 3200.98;
 cout << "张三\t" << s["张三"] << endl;
 cout << "里斯\t" << s["里斯"] << endl;
 cout << "王五\t" << s["王五"] << endl;
 s.display();
}
2 个回答

double &operator[](const char *Name)

注意 const 。

C++ 里,字符串字面量是常量字符串,不能匹配 char * 参数,只能用 const char *

应使用:

double &operator[](const string &Name) 
推荐问题
logo
Microsoft
子站问答
访问
宣传栏