访问类的私有成员的几种方法

#include<iostream>

class CBox
{
public://公有的函数成员
	//显式构造函数
	 explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0) :
		                                        m_length{ lv }, m_width{ wv }, m_height{ hv }
	{
		std::cout << "调用构造函数" << std::endl;		
	}
	//函数成员
	 double volume()
	{
		return m_length * m_width *m_height; //返回盒子的体积
	}
private://私有的数据成员   类的成员函数可以访问它
	double m_length;
	double m_width;
	double m_height;

	inline double volume1(); //类外定义函数的类内声明
	double volume2();
	friend double volume3(const CBox& aBox);
};
inline double CBox:: volume1()//类的内联函数
{
	return m_length;
}
 double CBox::volume2()//类外定义,类内声明的成员函数
{
	return m_length;
}
 double volume3(const CBox& aBox)// 友元函数
 {
	 return aBox.m_height * aBox.m_length * aBox.m_width;
 }
int main()
{
	//声明三个类对象
	CBox box1{ 78.0, 24.0, 18.0 };//调用构造函数
	CBox box2{8.0,5.0,1.0};//调用构造函数
	CBox box3;//调用默认参数的构造函数
	
	std::cout << "Volume of box1 :" << ' ' << box1.volume() << std::endl;
	std::cout << "Volume of box2 :" << ' ' << box2.volume() << std::endl;
	std::cout << "Volume of box3 :" << ' ' << box3.volume() << std::endl;
	std::cout << "Volume of box1 :" << ' ' << volume3(box1) << std::endl;

	system("pause");
	return 0;
}

 

posted @ 2018-04-20 15:03  *夜空中最亮的星*  阅读(7397)  评论(0编辑  收藏  举报