简体   繁体   中英

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 result.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM