关于C++友元书上例子不能编译通过……苦恼了,麻烦各位帮个忙
才开始学习C++,最近刚看到友元部分,把书上的例子敲进去之后,用C-FREE编译居然没通过,请问是什么问题呢,下面是构建栏里面显示的信息,最后面是源代码,麻烦了(整个例子是计算屏幕上两点距离的程序)
--------------------配置: MinGW3.4.5 - CUI Debug, 编译器类型: MinGW--------------------
检查文件依赖性...
正在编译 C:\Users\yuneng\Documents\C-Free\Temp\Main.cpp...
[Error] C:\Users\yuneng\Documents\C-Free\Temp\Main.cpp:24: instantiated from here
[Error] C:\PROGRA~1\C-FREE~1\mingw32\include\C__~1\348B92~1.5\bits\stl_iterator_base_types.h:129: error: no type named `iterator_category' in `class TPoint'
[Error] C:\PROGRA~1\C-FREE~1\mingw32\include\C__~1\348B92~1.5\bits\stl_iterator_base_types.h:130: error: no type named `value_type' in `class TPoint'
[Error] C:\PROGRA~1\C-FREE~1\mingw32\include\C__~1\348B92~1.5\bits\stl_iterator_base_types.h:131: error: no type named `difference_type' in `class TPoint'
[Error] C:\PROGRA~1\C-FREE~1\mingw32\include\C__~1\348B92~1.5\bits\stl_iterator_base_types.h:132: error: no type named `pointer' in `class TPoint'
[Error] C:\PROGRA~1\C-FREE~1\mingw32\include\C__~1\348B92~1.5\bits\stl_iterator_base_types.h:133: error: no type named `reference' in `class TPoint'
构建中止 Main: 6 个错误, 0 个警告
源代码如下:
#include<iostream>
#include<math.h>
using namespace std;
class TPoint
{
public:
TPoint(double a,double b)
{
x=a;
y=b;
cout<<"point:("<<x<<","<<y<<")"<<endl;
}
friend double distance(TPoint &a,TPoint &b);
private:
double x,y;
};
double distance(TPoint &a,TPoint &b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int main()
{
TPoint p1(2,3),p2(4,5);
cout<<"the distance between two point is:"<<distance(p1,p2)<<endl;
return 0;
}
[解决办法]
distance跟某个标准库函数的名字冲突了,说完
#include<iostream>#include<cmath>using namespace std;class TPoint{public: TPoint(double a, double b) { x = a; y = b; cout << "point:(" << x << "," << y << ")" << endl; } friend double m_distance(TPoint &a, TPoint &b);private: double x, y;};double m_distance(TPoint &a, TPoint &b){ return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));}int main(){ TPoint p1(2, 3), p2(4, 5); cout << "the distance between two point is:" << m_distance(p1, p2) << endl; return 0;}