gpt4 book ai didi

c++ - 为什么这个友元函数不能访问类的私有(private)成员?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:09 24 4
gpt4 key购买 nike

当我尝试从 extractHistogram() 实现中访问 GHistogram 类的 bins 私有(private)成员时出现以下错误:

error: 'QVector<double> MyNamespace::GHistogram::bins' is private
error: within this context

其中“在此上下文中”错误指向 extractHistogram() 实现。有谁知道我的友元函数声明有什么问题吗?

代码如下:

namespace MyNamespace{

class GHistogram
{

public:
GHistogram(qint32 numberOfBins);
qint32 getNumberOfBins();

/**
* Returns the frequency of the value i.
*/
double getValueAt(qint32 i);
friend GHistogram * MyNamespace::extractHistogram(GImage *image,
qint32 numberOfBins);

private:
QVector<double> bins;
};

GHistogram * extractHistogram(GImage * image,
qint32 numberOfBins);

} // End of MyNamespace

最佳答案

根据我的 GCC,上述代码无法编译,因为 extractHistogram() 的声明出现在它被友元编辑的类定义之后。编译器在 friend 语句上卡住,说 extractHistogram 既不是函数也不是数据成员。一切正常,当我将声明移到类定义之前时,可以访问 bins(并添加前向声明 class GHistogram; 以便编译器知道返回类型).当然,extractHistogram() 的代码应该写在命名空间内,或者通过

namesapce MyNameSpace {
// write the function here
}

GHistogram *MyNameSpace::extractHistogram( //....

关于c++ - 为什么这个友元函数不能访问类的私有(private)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2500670/

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