#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
class MyPointer {
public:
MyPointer(double x, double y)
{
p_x = x;
p_y = y;
}
double get_x() { return p_x; }
double get_y() { return p_y; }
friend void f_distance(MyPointer, MyPointer);
private:
double p_x, p_y;
};
void f_distance(MyPointer a, MyPointer b)
{
double result = sqrt(pow(abs(a.p_x-b.p_x),2),pow(abs(a.p_y-b.p_y),2));
cout << "distance:" << result << endl;
}
void mydistance(MyPointer a, MyPointer b)
{
double result = sqrt(pow(abs(a.get_x-b.get_x), 2), pow(abs(b.get_y - b.get_y), 2));
cout << "distance:" << result << endl;
}
int main()
{
MyPointer p1(0, 0), p2(5,0);
mydistance(p1, p2);
f_distance(p1, p2);
system("pause");
return 0;
}
友元函数
原创
©著作权归作者所有:来自51CTO博客作者李响Superb的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
友元(友元函数、友元类和友元成员函数)
有些情况下,允许特定的非成员函数访问一个类的私有成员,同时仍阻止一般的访问,这是很方便做到的。例如被重载的操作符,如输入或输出操作符,经常需要访问类的私有数据成
成员函数 友元函数 友元类 ios #include -
友元实例:友元类及友元函数
学习了c++这么久,一直没有对友元进行了解,据说友元不是特别好用(据说,不是我说的),因此直到今天才去了解。其实友元确实不是很常用,但友元功能确实很实用,它不但能够释放类中的非公有成员,同时还能保证了类的封装性。用户可以有选择为具体的类或函数赋予“通行证”。还是比较灵活的。比如:某个类去访问另一个类的私有成成员,或者一个函数去访问某个类的私有成员等等,都可以使用友元来实现。 下面就友元做了两个小例子,望高手指教。(每段代码都在不同的文件中)首先是关于友元类的代码,就一句话,很简单。。。Test.h:#ifndef TEST_H#define TEST_H#include<iostream
#include 友元函数 #endif #ifndef #define -
友元函数
友元函数是个函数,通过声明为某个类的友元函数,他可以访问这个类的所有成员变量 ...
友元函数 成员变量 其他