读几个小程序了解c++:Part 02(友元、常类型)

#include <cstring>
#include <iostream>
using namespace std;

/* 类的主要特点是信息隐藏与封装,友元函数是为了实现在类的外部访
   问类的私人成员(或保护成员),是一扇通向私人(保护)成员的后
   门,使得普通函数也可以访问封装在某一类的信息。
*/

class Girl; ///提前声明Girl类
class Boy{
public:
    Boy(string x, int y, int z):age(z){
        name=x, id=y;
    }
    void prit(Girl &);
    friend void outp(Boy &);            ///Boy的友元函数,是外部函数
    void prit_age();
    ~Boy(){}
private:
    string name;
    int id;
    const int age;                      ///常类型:程序运行期间的常类型数据不能改变
};

class Girl{///补充定义Girl类
public:
    Girl(string x, int y){
        name=x, id=y;
    }
    friend void Boy::prit(Girl &);      ///Girl的友元函数,同时是Boy的成员函数
    ~Girl(){}
private:
    string name;
    int id;
};

void outp(Boy &x){                      ///外部函数:不属于任何一个类
    Girl g1("Suffy", 456);
    cout<<"The boy's id:"<<x.id<<endl;    //通过外部函数调用Boy类
    cout<<"The boy's name:"<<x.name<<endl<<"Over02\n\n";

    x.prit(g1);                           //通过外部函数调用Boy类中Girl的友元函数来调用Girl的私人成员
}

void Boy::prit(Girl &x){
    cout<<"Boy's id: "<<id<<endl;
    cout<<"Boy's name: "<<name<<endl;
    cout<<"Girl's id: "<<x.id<<endl;
    cout<<"Girl's name: "<<x.name<<endl<<"Over01\n"<<endl;
}
void Boy::prit_age(){
    cout<<name<<"'s age is: "<<age<<endl;
}

void fuction01(){                       ///友元
    Boy b1("Moffy", 123, 18);
    Girl g1("Vicky", 321);
    b1.prit(g1);

    outp(b1);
}
void fuction02(){                       ///常类型
    Boy b1("Lucky", 234, 18);
    b1.prit_age();
}

int main(){
    ///fuction01();
    fuction02();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值