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

#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;
}

 

转载于:https://www.cnblogs.com/onlylove-miao/p/8890972.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值