C++ 访问类obj的私有数据
下面是函数C++ 访问类obj的私有数据,c++,C++,下面是函数操作符+重载使用操作符访问类的私有成员的代码。这有效吗?实际上我的问题是使用操作符。它们可以直接访问私有成员吗 #include <iostream> using namespace std; class Box { public: double getVolume(void) { return length * breadth * height; } void setLength( do
操作符+
重载使用
操作符访问类的私有成员的代码。这有效吗?实际上我的问题是使用
操作符。它们可以直接访问私有成员吗
#include <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length; //These are my problem
box.breadth = this->breadth + b.breadth; //These are my problem
box.height = this->height + b.height; //These are my problem
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Main function for the program
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
#包括
使用名称空间std;
类框
{
公众:
双卷(无效)
{
返回长度*宽度*高度;
}
空隙设置长度(双透镜)
{
长度=长度;
}
无效收进深度(双bre)
{
宽度=bre;
}
空隙设置高度(双高)
{
高度=高;
}
//重载+运算符以添加两个长方体对象。
接线盒操作员+(常数接线盒和b)
{
盒子;
box.length=this->length+b.length;//这是我的问题
box.width=this->width+b.width;//这是我的问题
box.height=this->height+b.height;//这是我的问题
返回框;
}
私人:
双倍长度;//长方体的长度
双宽度;//盒子的宽度
双倍高度;//盒子的高度
};
//程序的主要功能
int main()
{
Box Box1;//声明Box类型的Box1
Box Box2;//声明Box类型的Box2
Box Box3;//声明Box类型的Box3
double volume=0.0;//将盒子的体积存储在此处
//方框1规格
框1.设定长度(6.0);
框1.立根数(7.0);
框1.设置高度(5.0);
//方框2规格
框2.设定长度(12.0);
框2.立根数(13.0);
框2.设置高度(10.0);
//方框1的体积
volume=Box1.getVolume();
cout因为他们属于同一类型,所以他们是天生的朋友
C++允许朋友
访问另一个类的私有
方法和属性
有关更多信息,请参阅。,因为b
也是一个框(或所述框的派生)。所述成员函数(运算符+`)可以访问类,而不仅仅是当前实例(此).box.length=this->length+b.length;box.width=this->width+b.width;box.height=this->height+b.height;应该使用成员函数访问它们。我无法获取u?@Maizere私有属性不适用于friend
对象。但是操作符+不是friend函数,而不是friend函数它可以直接访问私人成员吗?