c/c++基础(十九) 友元

1.友元函数：

Point.类的声明与定义：

#pragma once
#ifndef _POINT_H
#define _POINT_H

class Point
{
public:
void getXY();
friend double distanceXY(Point &a,Point &b);

public:
Point(double x,double y);
~Point(void);

private:
double x;
double y;
};

#endif

#include "stdafx.h"
#include "Point.h"
#include<cmath>
#include<iostream>
using namespace std;

Point::Point(double x,double y)
{
this->x=x;
this->y=y;
}

Point::~Point(void)
{
}

void Point::getXY()
{
cout<<"x: "<<x<<" y: "<<y<<endl;
}

double distanceXY(Point &a,Point &b)
{
double dx=a.x-b.x;
double dy=a.y-b.y;
return sqrt(dx*dx+dy*dy);
}

#include "stdafx.h"
#include "Point.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
Point p1(3.0,4.0),p2(5,6);
p1.getXY();
p2.getXY();

double dis=distanceXY(p1,p2);
cout<<"distance is : "<<dis<<endl;
return 0;
}

#pragma once
class A
{
public:
void getXY();
friend class B;

public:
A(double x,double y);
~A(void);

private:
double x;
double y;
};


#include "stdafx.h"
#include "A.h"
#include<cmath>
#include<iostream>
using namespace std;

A::A(double x,double y)
{
this->x=x;
this->y=y;
}

A::~A(void)
{
}

void A::getXY()
{
cout<<"A x: "<<x<<"	y: "<<y<<endl;
}

#pragma once
#include "A.h"
class B
{

public:
B(void);
~B(void);

public:
void setX(A &a);
void setY(A &b);
};


#include "stdafx.h"
#include "B.h"

B::B(void)
{
}

B::~B(void)
{
}

void B::setX(A &a)
{
a.x=0;
a.getXY();
}

void B::setY(A &a)
{
a.y=0;
a.getXY();
}

#include "stdafx.h"
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
A a(5.0,5.0);
B b;
b.setX(a);
b.setY(a);

return 0;
}

M文件声明与定义：

#pragma once
#ifndef _M_H
#define _M_H

#include "N.h"
class M
{
public:
void getXY();
friend void N::print(M& m);

public:
M(double x,double y);
~M(void);

private:
double x;
double y;

private:
void getXY2();
};

#endif

#include "stdafx.h"
#include "M.h"
#include<cmath>
#include<iostream>
using namespace std;

M::M(double x,double y)
{
this->x=x;
this->y=y;
}

M::~M(void)
{
}

void M::getXY()
{
cout<<"M getXY x: "<<x<<"	y: "<<y<<endl;
}

void M::getXY2()
{
cout<<"我是M中的私有方法"<<endl;
}

N的声明与定义：

#pragma once
#ifndef _N_H
#define _N_H

class M;
class N
{

public:
N(void);
~N(void);

public:
void print(M &m);
void print2(M &m);
};

#endif

#include "stdafx.h"
#include "N.h"
#include "M.h"

N::N(void)
{
}

N::~N(void)
{
}

void N::print(M &m)
{
m.getXY();
m.getXY2();
}

void N::print2(M &m)
{
//m.getXY();//--------这里如果打开注释会报错
//m.getXY2();
}

#include "stdafx.h"
#include "M.h"
#include "N.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
M m(5.0,5.0);
N n;
n.print(m);
n.print2(m);
return 0;
}