C++友元函数的问题
这个程序是定义一个描述“点”的类,然后通过调用“点”类来定义一个描述“直线”的类。最后返回“直线”类的长度。使用的工具是visual studio 2010。代码如下。/stdafx.h
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <iostream>
using namespace std;
class cpoint
{
public:
cpoint(double X,double Y){x=X;y=Y;};
cpoint(cpoint& p);
friend cline::cline(cpoint& p1,cpoint& p2);
~cpoint(void);
private:
double x;
double y;
};
class cline
{
public:
cline(cpoint& p1,cpoint& p2);
~cline(void);
double getlength();
private:
cpoint cstart,cend;
double length;
};
/youyuan.cpp
#include "stdafx.h"
cpoint::cpoint(cpoint& p)
{
x=p.x;
y=p.y;
}
cline::cline(cpoint& p1,cpoint& p2):cstart(p1),cend(p2)
{
double xx,yy;
xx=fabs(p1.x-p2.x);
yy=fabs(p1.y-p2.y);
length=sqrt(xx+yy);
}
cline::~cline(void)
{
}
double cline::getlength()
{
return this->length;
}
int _tmain(int argc, _TCHAR* argv[])
{
cpoint p1(2,6),p2(3,7);
cline myline(p1,p2);
cout<<"the length of myline is:"<<myline.getlength()<<endl;
getchar();
return 0;
}
这时代码标红的地方会提示“成员cpoint::x不可访问”或“成员cpoint::y不可访问”。
———————————————————————————————————————————————————————————————
/stdafx.h
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <iostream>
using namespace std;
class cpoint;
class cline
{
public:
cline(cpoint& p1,cpoint& p2);
~cline(void);
double getlength();
private:
cpoint cstart,cend;
double length;
};
class cpoint
{
public:
cpoint(double X,double Y){x=X;y=Y;};
cpoint(cpoint& p);
friend cline::cline(cpoint& p1,cpoint& p2);
~cpoint(void);
private:
double x;
double y;
};
/youyuan.cpp
#include "stdafx.h"
cpoint::cpoint(cpoint& p)
{
x=p.x;
y=p.y;
}
cline::cline(cpoint& p1,cpoint& p2):cstart(p1),cend(p2)
{
double xx,yy;
xx=fabs(p1.x-p2.x);
yy=fabs(p1.y-p2.y);
length=sqrt(xx+yy);
}
cline::~cline(void)
{
}
double cline::getlength()
{
return this->length;
}
int _tmain(int argc, _TCHAR* argv[])
{
cpoint p1(2,6),p2(3,7);
cline myline(p1,p2);
cout<<"the length of myline is:"<<myline.getlength()<<endl;
getchar();
return 0;
}
将cline类的定义放在cpoint前边,则不会出现这个语法错误的提示。但是编译过程中,上边标红的位置会提示错误。错误提示如下“‘cline::cstart’使用未定义的 class‘cpoint’”,“‘cline::cend’使用未定义的 class‘cpoint’”。
请问一下,为什么cline和cpoint类的定义先后会赢下友元函数对私有类的访问,还有上述错误怎么解决。另外还有,如果想模块化编程,就是cline.h、cpoint.h、cline.cpp、cpoint.cpp里分别放各个类的声明和函数实体,在youyuan.cpp中实现主函数,各文件中应该包含哪些头文件。