友元函数访问私有报错
报错显示未定义标识符,请问问题出在哪里,谢谢!
#include
struct DataType
{
int ID;//编号
char name[10];//姓名
char ch;//性别
char phone[13];//电话
char addr[31];//地址
};
class Contact
{
public:
Contact();
Contact(int ID, char* name, char* ch, char* phone, char* addr);
~Contact();
void addContact(int ID, char* name, char* ch, char* phone, char* addr);
friend void deleteContact(char* name);
friend int GetLength();
private:
DataType person[100];
int m_ID;
char* m_name;
char* m_ch;
char* m_phone;
char* m_addr;
int length;
};
Contact::Contact()
{
person == new struct DataType;
}
Contact::Contact(int ID, char* name, char* ch, char* phone, char* addr)//构造
{
m_ID = ID;
m_name = name;
m_ch = ch;
m_phone = phone;
m_addr = addr;
}
void deleteContact(char* name)//删除联系人
{
//首先查找联系人
cout << "请输入要删除的联系人姓名:";
cin >> name;
int i = Locate(name);
//删除
DataType x = person[i - 1];
for (int j = i; j < length; j++)
person[j - 1] = person[j];
length--;
return x;
}
int GetLength()
{
return length;
}
参考GPT和自己的思路:您的代码中存在多处错误,导致编译错误。
首先,在 Contact 类的默认构造函数中,应该使用单个等于号(赋值),而不是双等于号(判断相等)。正确的写法如下所示:
Contact::Contact()
{
person = new struct DataType;
}
其次,在 deleteContact 函数中,您没有指定要删除的 Contact 对象所属的 Contact 实例。您需要将 deleteContact 函数定义为 Contact 类的友元函数,并将其实现改为以下形式:
void Contact::deleteContact(char* name)
{
//首先查找联系人
cout << "请输入要删除的联系人姓名:";
cin >> name;
int i = Locate(name);
//删除
DataType x = person[i - 1];
for (int j = i; j < length; j++)
person[j - 1] = person[j];
length--;
return x;
}
最后,在 GetLength 函数中,您没有指定要返回的 Contact 实例的 length 成员。您需要将其改为以下形式:
int Contact::GetLength()
{
return length;
}
除此之外,您的代码中还存在其它语法问题和逻辑问题,需要进一步修改和完善。