m0_74071629 2023-03-24 21:02 采纳率: 100%
浏览 15
已结题

友元函数访问私有报错

友元函数访问私有报错
报错显示未定义标识符,请问问题出在哪里,谢谢!

#include<iostream>

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;
}

  • 写回答

1条回答 默认 最新

  • IT_service_mesh 2023-03-24 21:09
    关注

    参考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;
    }
    

    除此之外,您的代码中还存在其它语法问题和逻辑问题,需要进一步修改和完善。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月2日
  • 已采纳回答 3月25日
  • 创建了问题 3月24日

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭