c++ - 我如何能够访问类的私有(private)数据成员?

标签 c++ oop

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

那么就完全没问题了,因为 thisd 都是类 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/

相关文章:

C++ double to hex console output need help in resolving

c++ 将数字的小数部分转换为整数

c++ - 删除 QString 中所有出现的特殊字符

C#-调用覆盖版本的方法的基本版本

c++ - OOP:自绘形状和吠狗

python - 如何使用 dunder 方法进行对象比较

C++ 想从基类调用派生函数

java - 为什么在 setOnClickListener() 中使用 (this)

python - 在两个 wxpython 选项卡之间共享变量

c++ - 使用 Rcpp 查找重复项