C++友元理解

来源:互联网 发布:linux shell脚本编写 编辑:程序博客网 时间:2024/06/01 08:59

为了是自己理解深刻,方便自己随时查找,也方便大家,特发此博客共享:直接上代码:

/*为了使类的private成员和protected成员可以被其他类和其他成员函数使用,引入了友元概念。友元函数:友元是普通函数或类的成员函数友元类:友元是一个类,类的所有成员函数称为友元函数。友元函数定义后可以访问该类的所有对象:private,protected,public成员。格式:friend<数据类型><友元函数名>(参数表)*/#include<iostream>#include<string>using namespace std;class Rectangle {public:Rectangle(double a = 0, double b = 0)//定义构造函数{length = a;width = b;}Rectangle(Rectangle &r); //重载构造函数double getlength() { return length; }double getwidth() { return width; }friend double area(Rectangle &rectangle); //声明外部友元函数/* 友元函数不是类的成员,所以不能直接引用对象成员的名字,也不能通过this指针引用对象成员,必须通过作为入口参数传递进来的对象名会对象指针来引用该对象成员。*/private:double length;double width;};double area(Rectangle &rectangle) // 定义友元函数{return (rectangle.length*rectangle.width);}/* 友元成员:一个类的成员函数是另一个类的友元函数。不仅可以访问自己类的各个成员,也可以访问友元类的各个成员。这种机制使得两个类可以互相访问。*/class boy;class girl {public:explicit girl(char *n, int a){name = new char[strlen(n)+ 1];//分配空间strcpy_s(name,sizeof(name), n); //调用字符串拷贝函数age = a;}void prt(boy &b);~girl() { delete name; }private:char *name;int age;};class boy {public:explicit boy(char *n, int a){name = new char[strlen(n) + 1];//分配空间strcpy_s(name, sizeof(name), n); //调用字符串拷贝函数age = a;}friend void girl::prt(boy &b);~boy() { delete name; }private:char *name;int age;};void girl::prt(boy &b){cout << "girl\'s name:"<<name<< "  age:" << age << "\n";//直接调用自己类的private成员cout << "boy\'s name:" <<b.name<< "  age:" << b.age << "\n"; //调用友元类的成员}//友元类可以实现类之间的数据共享int main(){/*Rectangle ob(4, 5); //友元函数用例cout << "The area is:" << area(ob)<<endl; */girl g1("szu", 15);//友元成员用例boy b1("Tec", 16);g1.prt(b1);system("pause");return 0;}


0 0
原创粉丝点击