gpt4 book ai didi

c++ - 嵌套类 C++,如何使外部方法成为嵌套类的友元

转载 作者:行者123 更新时间:2023-11-27 22:58:16 27 4
gpt4 key购买 nike

我需要从类 stos 的方法“pop”中的类信息中获取对私有(private)数据的访问权限。我知道我可以使用一种特殊的方法修改嵌套函数,但我认为它不像使用“ friend ”那样优雅。我想使外部方法成为嵌套类的 friend ,但我得到的信息是“不能重载仅由返回类型分离的函数”。有可能做到吗?

class stos
{
class info
{
int x;
bool isGood;
friend info pop(); // warning: cannot overload functions distungished by return type alone
};
static const int SIZE = 10;
int dane[SIZE];
bool isEmpty;
bool isFull;
int *top;
public:
stos();
info pop();
info push(int x);
};

编辑:

   stos::info stos::pop()
{
info objInfo;
if (isEmpty == true)
{
objInfo.isGood = false;
return objInfo;
}

objInfo.isGood = true;
objInfo.x = *top;
top--;
return objInfo;

}

最佳答案

您可以在stos 的开头声明info 类,然后再定义它。所以你可以把你的类的定义改成这样

class stos
{
class info;
^^^^^^^^^^ Declare it here

... rest of class

public:
info pop();

private:
class info
{
int x;
bool isGood;
friend info stos::pop();
^^^^ Added surrounding class for overload resolution
}; //Define it here
};

这应该会阻止错误。

关于c++ - 嵌套类 C++,如何使外部方法成为嵌套类的友元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401561/

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