一个构造函数可以是c ++中的朋友吗? [英] Can a constructor function be a friend in c++?
本文介绍了一个构造函数可以是c ++中的朋友吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以将类的构造函数声明为朋友吗?我想它不能。但我读的地方,它可以是,但我无法做到。如果是的话,请提供一些示例代码。
Can we declare constructor of a class to be friend? I think it cannot be. But i read somewhere that it can be, but i was unable to do. If yes can you please provide some example code.
推荐答案
可以:
class Y
{
public:
Y();
};
class X
{
private:
void foo() {}
friend Y::Y();
};
Y::Y()
{
X x; x.foo();
}
按 11.3朋友[class.friend]
5)当朋友声明引用重载的名称或操作符时,只有参数类型指定的函数成为朋友。 类X的A
成员函数可以是类Y的朋友。
[示例:
class Y {
friend char* X::foo(int);
friend X::X(char); // constructors can be friends
friend X::~X(); // destructors can be friends
};
-end示例]
—end example ]
(强调我)
这篇关于一个构造函数可以是c ++中的朋友吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文