訪問類的私有成員的幾種方法


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM