您的位置:首页 > 编程语言 > C语言/C++

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

2018-02-28 20:29 531 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐