我正在学习 C++ 中的 OOP,我几乎了解它的大部分基础知识。但这是我的查询。我了解到我们无法从其他对象访问私有(private)数据成员。但我有一个代码片段似乎是这样做的。它工作完美,但我想知道,这段代码为什么以及如何工作?这不是违反了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;
}
这怎么可能?
最佳答案
如果您指的是这部分代码:
void add(Dist d){
this->feet = this->feet + d.feet;// accessing private data members!
this->inches = this->inches + d.inches;
/* ... */
}
那么就完全没问题了,因为 this
和 d
都是类 Dist
的对象。重要的是它们是相同的类,而不是相同的对象。
参见Why do objects of the same class have access to each other's private data?详细解释。
关于c++ - 我如何能够访问类的私有(private)数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35526249/