开发者

Friend-ing a type?

I don't know the correct key to search for this type of friend on the Internet, simply a keyword friend alone won't bring this expected resu开发者_StackOverflowlt.

class Integer
{
   friend int;
};

What does friend int means ?


It's invalid C++, it should be rejected by your compiler. g++ gives the two errors "error: a class-key must be used when declaring a friend" and "error: invalid type ‘int’ declared ‘friend’".

It's only meaningful if the thing which is being "friend"ed is a function or class name. In that case, the named function, or all of the member functions of the named class, can access your class's private and protected members as if they were public.

For example:

class MyClass
{
public:
  int x;
protected:
  int y;
private:
  int z;

  friend void SomeFunction(const MyClass& a);  // Friend function
  friend class OtherClass;  // Friend class
};

void SomeFunction(const MyClass& a)
{
  std::cout << a.x << a.y << a.z;  // all ok
}

void AnotherFunction(const MyClass& a)
{
  std::cout << a.x << a.y << a.z;  // ERROR: 'y' and 'z' are not accessible
}

class OtherClass
{
  void ClassMethod(const MyClass& a)
  {
    std::cout << a.x << a.y << a.z;  // all ok
  }
};

class ThirdClass
{
  void ClassMethod(const MyClass& a)
  {
    std::cout << a.x << a.y << a.z;  // ERROR: 'y' and 'z' not accessible
  }
};


friend int means nothing. If you search for "C++ friend class" you will find information about what friends can be used for. Basically it lets the friend access private (or protected) members of the class. In the example you gave it's pointless because int is not a class that would ever attempt to access another class's internals.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜