万俟淋曦 2021-11-02 16:48 采纳率: 0%
浏览 35

私有成员函数可以声明为其他类的友元吗?

如题,同样是私有函数做友元,两段代码一个报错一个不报错:

这段不报错

#include <iostream>
using namespace std;

// forward declare
class A;
class B;

// class declare
class B
{
public:
    void saysomething(A& a);
private:
    void saybye(A& a);
    friend class A;
};

class A
{
    friend void B::saybye(A&);
private:
    void sayhi();
};

// method declare
void A::sayhi()
{
    cout << "hi" << endl;
}

void B::saysomething(A& a)
{
    saybye(a);
}

void B::saybye(A& a)
{
    a.sayhi();
    cout << "bye" << endl;
}

int main(void)
{
    A a;
    B b;
    b.saysomething(a);
    return 0;
}

这段报错:

1.cpp: In function ‘int main()’:
1.cpp:24:5: error: ‘int Scale::getWeight(IceCream)’ is private
 int Scale::getWeight(IceCream obj)
     ^
1.cpp:33:75: error: within this context
     cout << "DairyQueen's totalWeight is: " << eScale.getWeight(dairyQueen) << endl;
                                                                           ^

代码:

#include <iostream>
using namespace std;

class IceCream;

class Scale
{
private:
    int getWeight(IceCream obj);
    friend class IceCream;
};

class IceCream
{
    // 其他类的成员函数声明为友元
    friend int Scale::getWeight(IceCream obj);
private:
    int totalWeight = 10;
};

// 类Scale的成员函数
int Scale::getWeight(IceCream obj)
{
    return obj.totalWeight;
}

int main()
{
    IceCream dairyQueen;
    Scale eScale;
    cout << "DairyQueen's totalWeight is: " << eScale.getWeight(dairyQueen) << endl;
    return 0;
}

请问这个哪里有问题吗?

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-07 17:42
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 11月2日

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测