zoukankan      html  css  js  c++  java
  • 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去掉,那么函数就会报错。

  • 相关阅读:
    杂谈-论时间成本
    java笔记:排错5:误删maven target:恢复不了,怎么再生成
    十大经典排序(转发帖)
    java笔记(Idea,Maven):误删maven项目的target的class,怎么再生成target
    JDK解压版制作
    日常报错记录4:ssh工程复制粘贴顺序。
    欧朋Opera 浏览器(打不开百度)提示“您的连接不是私密连接”,解决办法
    日常报错记录2: MyBatis:DEBUG [main]
    JavaWeb-SQL-Servlet-JSP学做购物系统——日志一
    git 命令
  • 原文地址:https://www.cnblogs.com/ligei/p/11451905.html
Copyright © 2011-2022 走看看