我正在用C++学习OOP,并且我非常了解它的大部分基础知识。但这是我的问题。我了解到,我们无法从其他对象访问私人数据成员。但我有一个代码片段,似乎是这样做的。它的工作完美,但我想知道,为什么以及这个代码是如何工作的?这不是违反OOP规则吗?我如何能够访问某个班级的私人数据成员?
下面是代码:
#include "iostream"
using namespace std;
class Dist {
int feet; //private by default
float inches; //private by default
public:
void getdata()
{
cout<<"Enter the feets: ";
cin>>feet;
cout<<"Enter the inches: ";
cin>>inches;
}
void putdata()
{
cout<<"Data is "<<feet<<"\' "<<inches<<"\" "<<endl;
}
void add(Dist d)
{
this->feet = this->feet + d.feet;// accessing private data members!
this->inches = this->inches + d.inches;
if (this->inches >= 12) {
this->feet++;
this->inches = this->inches - 12;
}
}
};
int main()
{
Dist d1,d2;
d1.getdata();
d2.getdata();
d1.add(d2);
d1.putdata();
return 0;
}
这怎么可能?
但是,d是一个不同的对象。 –
这是一个很好的观点,但没关系。如果不允许写复制构造函数,那将很难! – Bathsheba
理论上,语言可能需要一个类来“朋友”本身,以允许访问其他对象的“私人”成员。我从来没有想过认真对待这个问题,这个想法只是在我脑海中... –