对于友元类,大家应该不陌生了,友元类声明会将整个类说明成为另一个类的友元关系,友元类的所有成员函数都可以是另一个类的友元函数;昨天在调试程序的时候,当我把所有程序写在一个文件中的时候,包括类和友元类的实现,还有main函数,编译能通过,而且也能执行,但是当我把类的定义和实现分开来的时候,就编译通不过了,具体代码如下
myPoint.h
#ifndef _myPoint_H_
#define _myPoint_H_
//#include "Line.h"//这里如果加上这条就会编译通不过,去掉后就能编译通过,也可以执行,不知道为什么
class line;
class myPoint{
private:
float x;
float y;
static int count;
public:
myPoint();
~myPoint();
myPoint(myPoint& point);
myPoint(float x, float y);
void display();
friend class Line;
friend float fdis(myPoint& p1, myPoint& p2);
};
#endif
myPoint.cpp
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include "myPoint.h"
using namespace std;
int myPoint::count = 0;
myPoint::myPoint(void){
this->count++;
}
myPoint::myPoint(myPoint& p){
this->x = p.x;
this->y = p.y;
this->count++;
}
myPoint::myPoint(float x, float y){
this->x = x;
this->y = y;
this->count++;
}
myPoint::~myPoint(void){
}
void myPoint::display(){
cout<<"myPoint:("<<this->x<<","<<this->y<<")"<<endl;
cout<<"当前是第"<<this->count<<"坐标点"<<endl;
}
float fdis(myPoint& p1, myPoint& p2){
float f1 = p1.x - p2.x;
float f2 = p2.y - p2.y;
float d = pow(f1, 2) + pow(f2, 2);
d = sqrt(d);
return d;
}
Line.h
#ifndef _LINE_H_
#define _LINE_H_
#include "myPoint.h"
class Line{
public:
Line(){}
~Line(){}
Line(Line& line);
Line(myPoint& pp1, myPoint& pp2);
float getLength();
private:
myPoint p1;
myPoint p2;
};
#endif
Line.cpp
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include "Line.h"
using namespace std;
Line::Line(Line &line){
this->p1 = line.p1;
this->p2 = line.p2;
}
Line::Line(myPoint& pp1, myPoint& pp2){
this->p1 = pp1;
this->p2 = pp2;
}
float Line::getLength(){
float f1 = this->p1.x - this->p2.x;
float f2 = this->p1.y - this->p2.y;
float d = pow(f1, 2) + pow(f2, 2);
d = sqrt(d);
return d;
}
有谁知道为什么在myPoint.h中加上#include "Line.h"会编译通不过?