C++ 友元类成员的问题

来源:百度知道 编辑:UC知道 时间:2024/09/28 05:27:13
#include <iostream>

using std::endl;
using std::cout;

class CCarton;

class CBottle
{
public:
CBottle::CBottle(double height, double diameter) : m_Height(height), m_Diameter(diameter)
{}

private:
double m_Height;
double m_Diameter;

friend CCarton::CCarton(const CBottle& aBottle); //.............
};

class CCarton
{
public:
CCarton::CCarton(const CBottle& aBottle)
{
m_Height = aBottle.m_Height; // 不能访问CBottle类的私有成员
m_Lenght = 4.0 * aBottle.m_Diameter;
m_Width = 3.0 * aBottle.m_Diameter;
}
private:
double m_Lenght;
double m_Width;
double m_Height;
};

int main()
{

return 0;
}

编译不通过....

不能把一个类的构造函数写成另一个类的友元么?

书上这么写的..
不是没有main()问题,我写了,我是针对我注释的两行的疑问,既然CCarton的构造函数已经是CBox的友元了,为什么还不能访问CBox的成员

答案是:当然可以。
不仅是一个函数,就是整个类也可以作为另一个类的友元。
正确程序如下:
#include <iostream>
using namespace std;

class CBottle;

class CCarton
{
public:
CCarton::CCarton(const CBottle& aBottle);

private:
double m_Lenght;
double m_Width;
double m_Height;
};

class CBottle
{
public:
CBottle::CBottle(double height, double diameter) : m_Height(height), m_Diameter(diameter)
{}

private:
double m_Height;
double m_Diameter;

friend CCarton::CCarton(const CBottle& aBottle); // .............

};

CCarton::CCarton(const CBottle& aBottle) //友元函数的定义要放于后面
{
m_Height = aBottle.m_Height;
m_Lenght = 4.0 * aBottle.m_Diameter;
m_Width = 3.0 * aBottle.m_Diameter;
}

int main()
{
return 0;
}
注释中说得很清楚了。
以上程序在VS2005中正确运行。
补充一点:若是在VC6.0中运行,请使用头文件:#include<iostream.h>
不要用u