【C++】cannot access private member declared in class 'Box'

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lyq_12/article/details/84952603

私有的成员和受保护的成员不能使用直接成员访问运算符 (.) 来直接访问。

1、问题代码

#include <iostream>
using namespace std;

class  Box
{
private:
	double length;   //长度
	double width;    //宽度
	double height;   //高度
};

int main()
{
	Box box1;
	Box box2;

	double volume = 0;

	//box1
	box1.length = 5;
	box1.width  = 6;
	box1.height = 7;

	//box2
	box2.length = 10;
	box2.width  = 11;
	box2.height = 12;

	volume = box1.height*box1.length*box1.width;
	cout<<volume<<endl;

	volume = box2.height*box2.length*box2.width;
	cout<<volume<<endl;

	system("pause");
	return 0;
}

2、修改后的代码

#include <iostream>
using namespace std;

class  Box
{
public:
	double length;   //长度
	double width;    //宽度
	double height;   //高度
};

int main()
{
	Box box1;
	Box box2;

	double volume = 0;

	//box1
	box1.length = 5;
	box1.width  = 6;
	box1.height = 7;

	//box2
	box2.length = 10;
	box2.width  = 11;
	box2.height = 12;

	volume = box1.height*box1.length*box1.width;
	cout<<volume<<endl;

	volume = box2.height*box2.length*box2.width;
	cout<<volume<<endl;

	system("pause");
	return 0;
}

结果:

猜你喜欢

转载自blog.csdn.net/lyq_12/article/details/84952603