如何访问类的私有数据成员

How am I able to access private data members of a class?

本文关键字:数据成员 何访问 访问      更新时间:2023-10-16

我正在学习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;
}

这怎么可能?

如果你的意思是这部分代码:

void add(Dist d){
    this->feet = this->feet + d.feet;// accessing private data members!
    this->inches = this->inches + d.inches;
    /* ... */
}

那么这完全没问题,因为thisd都是类Dist的对象。重要的是它们是同一个,而不是同一个对象

有关详细说明,请参阅为什么同一类的对象可以访问彼此的私有数据?

不,没关系。对私有成员的访问仅限于类中的函数;无论函数本身是私有的、受保护的还是公共的。

由于函数是公共函数,因此可以通过类的实例访问它们。

请注意,将类实例作为参数的函数也可以访问这些函数的私有成员 - 如果不是这种情况,那么很难编写复制构造函数和赋值运算符等代码。

私有意味着您无法从类外部访问数据。

课程的其他成员仍然可以访问它们,即使他们自己是公开的。

类似的东西

d1.feet;

不过是无效的。