C++友元函数和友元类

友元函数(全局函数) : 
成员函数具有this指针,友元函数没有this指针;
       友元函数是可以直接访问类的私有成员的非成员函数。它是定义在类外的普通函数,它不属于任何类,但需要在类的定义中加以声明,声明时只需在友元的名称前加上关键字friend,其格式如下:
       friend 类型 函数名(形式参数);
       友元函数的声明可以放在类的私有部分,也可以放在公有部分,它们是没有区别的,都说明是该类的一个友元函数。
       一个函数可以是多个类的友元函数,只需要在各个类中分别声明。
       友元函数的调用与一般函数的调用方式和原理一致。
友元类 : 
       友元类的所有成员函数都是另一个类的友元函数,都可以访问另一个类中的隐藏信息(包括私有成员和保护成员)。       
       当希望一个类可以存取另一个类的私有成员时,可以将该类声明为另一类的友元类。定义友元类的语句格式如下:
       friend class 类名;
       其中:friend和class是关键字,类名必须是程序中的一个已定义过的类。


#include<iostream> class Dog; class Cat; void eat(const Dog &dog,const Cat &cat); class Dog { private: int Dwater; int Dfood; friend class Cat; // 友元类 public: Dog(const int food=50, const int water=30):Dfood(food),Dwater(water) { std::cout <<"now dog's food is: "<<Dfood<<std::endl; std::cout << "now dog's water is: "<<Dwater<<std::endl; } void hobby(); friend void eat(Dog &dog,Cat &cat); // 友元函数 }; class Cat { private: int Cwater; int Cfood; public: Cat(const int food=20,const int water=10):Cwater(water),Cfood(food){ std::cout << "now cat's food is: "<<Cfood<<std::endl; std::cout << "now cat's' water is: "<<Cwater<<std::endl; } void rob(const Dog &dog); void hobby(); friend void eat(Dog &dog,Cat &cat); // 友元函数 }; void Dog::hobby(){ std::cout << "dog like play."<<std::endl; } void eat(Dog &dog,Cat &cat){ std::cout << "dog's food is: "<<dog.Dfood<<std::endl; std::cout << "dog's water is: "<<dog.Dwater<<std::endl; std::cout << "cat's food is: "<<cat.Cfood<<std::endl; std::cout << "cat's water is: "<<cat.Cwater<<std::endl; } void Cat::hobby(){ std::cout << "cat's hobby is sleep"<<std::endl; } void Cat::rob(const Dog &dog){ int newfood=Cfood+dog.Dfood; std::cout <<"the cat likes robbing the dog's food."<<std::endl; std::cout << "the cat's new food is: "<<newfood<<std::endl; } int main(){ Dog dog(100,50); dog.hobby(); Cat cat(20,10); cat.hobby(); cat.rob(dog); return 0; }

注意:如果将class Dog 里friend class Cat的friend去掉,那么函数就会报错。

posted @ 2019-09-03 11:19  hiligei  阅读(154)  评论(0编辑  收藏  举报