#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) |