Chinaunix首页 | 论坛 | 博客
  • 博客访问: 16198
  • 博文数量: 14
  • 博客积分: 245
  • 博客等级: 二等列兵
  • 技术积分: 180
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-28 13:45
文章分类

全部博文(14)

文章存档

2013年(9)

2012年(5)

我的朋友

分类: C/C++

2012-12-28 14:07:19

#include "stdafx.h"
#include
class cat
{
public:
 friend void setCatHigh(cat* wendy,int value);
 friend void setCatWeight(cat* wendy,int value);
 friend void setCatColor(cat* wendy,int value);
public:
 void getCatInfo(int &high,int &weight,int &color);
private:
 int high;
 int weight;
 int color;
};
void setCatHigh(cat* wendy,int value)
{
 wendy->high = value;
}
void setCatWeight(cat* wendy,int value)
{
 wendy->weight = value;
}
void setCatColor(cat* wendy,int value)
{
 wendy->color = value;
}
void cat::getCatInfo(int &high,int &weight,int &color)
{
 high = this->high;
 weight = this->weight;
 color = this->color;
}
int _tmain(int argc, _TCHAR* argv[])
{
 cat kity;
 int high =0;
 int weight =0;
 int color = 0;
 setCatHigh(&kity,2);
 setCatWeight(&kity,3);
 setCatColor(&kity,4);
 kity.getCatInfo(high,weight,color);
 std::cout<<"high is "<       <<"weight is "<    <<"color is "<
 return 0;
}
 
从这个例子中,可以看出:
1、友元函数虽然声明在类里面,但是不隶属于类。再进行CPP中,不需要cat::的头,而是直接使用。
2、友元函数可以对类中的私有成员进行访问。
 
那为什么不用成员函数,而要用友元函数呢?这样的设计好在哪里?还是为了解决某个无法解决的问题。
他们的适用场景又在哪里?
阅读(144) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~