书上有这么个例子,A类先定义,B类后定义,但A中的成员函数就可以放在B中当友元函数访问B的私有数据

,这样就对。反之,B类先定义,A类后定义,就我这个程序例子就验证不行。是不是这样?那为什么会这样?请解释

#include <IOSTREAM>
using namespace std;
#define pi 3.1415926

class Cylinder;
class Circle
{
private:
double radius;
public:
Circle(double r){radius=r;}
double GetAreaCircle()
{
return pi*radius*radius;
}
friend double Cylinder::GetAreaCylinder();//错误
};

class Cylinder:public Circle
{
private:
double height;
public:
Cylinder(double h,double r):Circle(r)
{
height=h;
}
double GetAreaCylinder()
{
return 2*GetAreaCircle()+2*pi*radius*height;//错误
}
double GetVolumeCylinder()
{
return GetAreaCircle()*height;
}
};
void main()
{
Cylinder cyl(1,2);
cout<<cyl.GetAreaCylinder()<<endl;
cout<<cyl.GetVolumeCylinder()<<endl;
}

第1个回答  推荐于2016-11-20
前向声明的类不能使用该类的具体的函数

声明一个foo类,这个声明,有时候也叫做前向声明(forward declaration),在声明完这个foo类之后,定义完这个foo类之前的时期,foo类是一个不完全的类型(incomplete type),也就是说foo类是一个类型,但是这个类型的一些性质(比如包含哪些成员,具有哪些操作)都不知道。
因此这个类的作用也很有限.
(1)不能定义foo类的对象。
(2)可以用于定义指向这个类型的指针或引用。(很有价值的东西)
(3)用于声明(不是定义)使用该类型作为形参或者返回类型的函数。追问

friend double Cylinder::GetAreaCylinder();//错误
你好,这句帮我解释下

因为Cylinder类不知道有这个操作?

追答

因为在Circle类内,Cylinder尚未定义完,此时仅仅知道有个类名叫Cylinder,但是具体实现是什么样的,此时不知道。也就是说Cylinder::GetAreaCylinder() 这个函数的地址是找不到的

本回答被提问者和网友采纳
相似回答