为什么友元类在静态函数调用时崩溃?
#include <iostream>
using namespace std;
class CClass
{
private:
friend class CFriend;
static void privateFunc(){std::cout << "privateFunc" << std::endl;};
};
class CFriend
{
public:
void privateFunc(){privateFunc();};
};
int main(int argc, char* argv[])
{
CFriend b;
b.privateFunc();
return 0;
}
此代码可以编译,但使用 gcc 编译器或 http://www.ideone.com/ 程序崩溃。这是编译器错误还是我需要了解有关友元类的更多信息?
#include <iostream>
using namespace std;
class CClass
{
private:
friend class CFriend;
static void privateFunc(){std::cout << "privateFunc" << std::endl;};
};
class CFriend
{
public:
void privateFunc(){privateFunc();};
};
int main(int argc, char* argv[])
{
CFriend b;
b.privateFunc();
return 0;
}
This code compiles, but using the gcc-compiler or http://www.ideone.com/ the program crashes. Is that a compiler error or do I need to understand more about friend classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您已经创建了无限递归:
请改为使用:
友元声明没有任何问题。
You've created infinite recursion:
Use instead:
There's nothing wrong with friend declaration.
对象中的无限递归,创建堆栈溢出!!!
您必须明确调用您的朋友类:
Infinite recursion in your object, creating a Stack Overflow !!!
You must explicitely call your friend class :
CFriend 类中也有名为
privateFunc()
的函数。这意味着当您在该函数内部调用privateFunc()
时,它将调用自身(它如何知道您指的是另一个类),从而进入递归无限循环。您的意思是
使用
CClass::
来完全指定您所指的函数的名称。You have the function called
privateFunc()
in CFriend class as well. This means when inside that function you callprivateFunc()
it will call itself (how should it know you mean the other class) thus entering a recursive infinite loop.You mean
using
CClass::
to specify completely the name of the function you mean.由于堆栈溢出而崩溃,您将通过范围解析来调用静态函数
It is crashing because of stack overflow you would beed scope resolution to call static function
无限递归函数导致堆栈溢出。 CFriend::privateFunc 正在调用自身。将其更改为
void privateFunc() {CClass::privateFunc();}
范围区别,公共、私有、受保护和友元,根本没有运行时后果。它们严格由编译器来决定什么是合法的或不合法的。您可以
#define private public
并且生成的可执行文件不会改变。You have a stack overflow from an infinitely recursive function. CFriend::privateFunc is calling itself. Change it to
void privateFunc() {CClass::privateFunc();}
Scope distinctions, public, private, protected and friend, have not runtime consequences at all. They are strictly for the compilier to decide what is legal or not. You could
#define private public
and the resulting executable wouldn't change.