我有一个演示程序来了解友元功能。我猜我被与前向声明相关的错误困扰了。
我有一个具有 x 和 y 坐标的点类。线类有两个点类对象。现在我在 line 类中有一个函数可以计算线的斜率。
这是我的程序:
#include <iostream>
using namespace std;
class point
{
int x,y;
public:
point(int,int);
point();
friend float line::slope();
};
point::point(int a, int b)
{
x=a;
y=b;
}
point::point()
{
}
class line
{
point p1,p2;
public:
line(point,point);
float slope();
};
line::line(point p1, point p2)
{
this->p1=p1;
this->p2=p2;
}
float line::slope()
{
float s;
s=((float)p2.y-p1.y)/(p2.x-p1.x);
return s;
}
int main()
{
float sl;
point obj(5,10);
point obj1(4,8);
line obj3(obj,obj1);
sl=obj3.slope();
cout<<"\n slope:"<<sl;
return 0;
}
由于以下原因,它给我关于前向声明的编译器错误:
当我首先尝试定义线类时,它不知道点类。即使我转发声明点类,这也不足以创建点类的对象,编译器应该知道点类的大小,因此知道整个类本身。通过这个答案中的解释理解它:https://stackoverflow.com/a/5543788
如果我先定义点类,它需要知道友元函数斜率,因此需要知道类线。 所以我尝试在定义点类之前像这样提供线类和斜率函数的前向声明:
class line;
float line::slope(); class point { int x,y; public: point(int,int); point(); friend float line::slope(); };
现在这给了我以下错误:
friend1.cpp:5: error: invalid use of incomplete type ‘struct line’
friend1.cpp:4: error: forward declaration of ‘struct line’
friend1.cpp:13: error: invalid use of incomplete type ‘struct line’
friend1.cpp:4: error: forward declaration of ‘struct line’
friend1.cpp: In member function ‘float line::slope()’:
friend1.cpp:9: error: ‘int point::y’ is private
friend1.cpp:43: error: within this context
friend1.cpp:9: error: ‘int point::y’ is private
friend1.cpp:43: error: within this context
friend1.cpp:9: error: ‘int point::x’ is private
friend1.cpp:43: error: within this context
friend1.cpp:9: error: ‘int point::x’ is private
friend1.cpp:43: error: within this context
.3。接下来,我尝试在 point.h 和 point.cpp 中分离出点类,在 line.h 和 line.cpp 中分离出线类。但仍然存在相互依赖。
虽然这在理论上应该是可行的,但我不知道如何让它工作。
寻找答案。
谢谢,
拉吉
PS:本程序是为了单独演示友元函数的使用。友元函数有两种类型,这是处理第二种类型的努力:
- 独立的友元函数。
- 属于另一个类的友元函数。
因此,在这种情况下排除了友元类的使用。
最佳答案
添加行
作为 friend
,而不仅仅是一个方法:
friend class line;
其他备注:
- 在头文件和实现文件中将声明与实现分开。
- 比
using
指令更喜欢完全限定(即删除using namespace std;
并改用std::cout
。 - 对于复杂类型更喜欢按引用传递 - 将
line(point,point);
更改为line(const point&, const point&);
编辑 出于教育目的 - 您不能像现在的代码那样将该特定函数声明为友元,因为没有 line
类的完整定义。因此,以下是唯一的方法:
class point;
class line
{
point *p1,*p2;
public:
line(point,point);
float slope();
};
class point
{
int x,y;
public:
point(int,int);
point();
friend float line::slope();
};
您转发声明 point
并将 line
中的 point
成员更改为 point*
(因为 point 是'一个完整的类型)。在 point
中,您现在拥有 line
类的完整定义,因此您可以将该方法声明为 friend。
编辑 2:对于这种特殊情况,不可能在 line
中使用 point
对象,因为您需要完整的类型。但是 line
也必须被完全定义,以便将其成员声明为 friend
。
关于c++ - 前向声明的问题 - 友元函数和线/点类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11771849/