25

我们可以将类的构造函数声明为朋友吗?我认为不可能。但我在某处读到它可能是,但我做不到。如果是,请提供一些示例代码。

4

1 回答 1

29

Yes it can:

class Y
{
public:
     Y();
};
class X
{
private:
     void foo() {}  
     friend Y::Y();
};
Y::Y() 
{
   X x; x.foo(); 
}  

As per 11.3 Friends [class.friend]

5) When a friend declaration refers to an overloaded name or operator, only the function specified by the parameter types becomes a friend. A member function of a class X can be a friend of a class Y.

[ Example:

class Y {
friend char* X::foo(int);
friend X::X(char); // constructors can be friends
friend X::~X(); // destructors can be friends
};

—end example ]

(emphasis mine)

于 2013-08-19T09:22:05.063 回答