gpt4 book ai didi

c++ - 类之间的信息丢失

转载 作者:行者123 更新时间:2023-12-02 10:31:13 25 4
gpt4 key购买 nike

对于我在 C++ 中的一个编程类(class),我们需要设计一个配对代理,并且在我创建一个新客户端后,它会以某种方式将其添加到运营商的 += 到客户端数组中,然后在 MENU 类中数据库丢失了客户端,我可以好像没找到原因。

添加客户端运算符(operator)

MatchmakingAgency& MatchmakingAgency:: operator+=( Client& c1)
{
if (m_clients)//Client** m_clients;
{
m_length++;
Client** newArr = new Client * [m_length];
if (!newArr)
{
cout << " Memory allocation failed!" << endl;
return *this;
}
//copy old array to new
for (int i = 0; i < m_length - 1; i++)
{
newArr[i] = m_clients[i];
}
newArr[m_length - 1] = &c1;
//delete allocation
delete[] m_clients;
m_clients = newArr;
delete[] newArr;
}
else //m_clients is empty
{
m_length = 1;
m_clients = new Client * [1];

if (!m_clients)
{
cout << " Memory allocation failed!" << endl;
return *this;
}
m_clients[0]= &c1;
}
return *this;
}

**菜单添加客户//来自用户的所有客户信息**
{

char temp[20]; //pointer to dynamically allocated data
char gender;
int age;
int num_of_hobbies;
cout << " enter ID number -> ";
cin >> temp;
String id = temp;
cout << "\n enter name -> " ;
cin.ignore();
cin.getline(temp,20);
String name = temp;
cout << "\n enter gender F/M-> " ;
cin >> gender;
cout << "\n enter age -> " ;
cin >> age;
if (age < 18)
{
cout << " Not in appropriate age! " << endl;
return;
}
cout << "\n enter number of hobbies -> " ;
cin >> num_of_hobbies;
cout << '\n';
char** hobby = new char* [num_of_hobbies];
if (!hobby)
{
cout << "memory allocation failed!" << endl;//show message
return;//go back
}
cout << "\n enter hobbies -> " << endl;
cin.ignore();
for (int i = 0; i < num_of_hobbies; i++)
{
cin.getline(temp,20);
hobby[i] = new char[(int)(strlen(temp)) + 1];
for(int j=0;j<=(int)strlen(temp);j++)
hobby[i][j] = temp[j];
}


Client cl1(id, name, gender, age, num_of_hobbies, hobby);
m_data_base.operator+=(cl1);
**//right here the m_data_base lost client info**
for (int i = 0; i < num_of_hobbies; i++)
delete[] hobby[i];
delete[] hobby;
}

最佳答案

您已将客户端指针复制到 newArr,添加新的,然后在将 m_clients 设置为 newArr 指针后,您通过删除 newArr 指针删除刚刚复制的所有内容。

    delete[] m_clients;
m_clients = newArr;
delete[] newArr;

关于c++ - 类之间的信息丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62174313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com