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日

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?