如何访问类的私有数据成员
How am I able to access private data members of a class?
我正在学习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;
/* ... */
}
那么这完全没问题,因为this
和d
都是类Dist
的对象。重要的是它们是同一个类,而不是同一个对象。
有关详细说明,请参阅为什么同一类的对象可以访问彼此的私有数据?
不,没关系。对私有成员的访问仅限于类中的函数;无论函数本身是私有的、受保护的还是公共的。
由于函数是公共函数,因此可以通过类的实例访问它们。
请注意,将类实例作为参数的函数也可以访问这些函数的私有成员 - 如果不是这种情况,那么很难编写复制构造函数和赋值运算符等代码。
私有意味着您无法从类外部访问数据。
课程的其他成员仍然可以访问它们,即使他们自己是公开的。
类似的东西
d1.feet;
不过是无效的。
相关文章:
- 用于访问容器<T>数据成员的正确 API
- 使用指针访问数组中的对象数据成员
- 友元函数无法访问私有数据成员 (c++)
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 访问数据成员(本身是对象)的数据成员,就好像它们是类成员一样
- 使公共数据成员在C++中无法访问
- 有没有办法在C++中循环访问对象的不同数据成员
- C++:成员不可访问-使用友元函数允许一个类修改另一个类的成员数据
- 如何在C++中使用类对象访问指针数据成员
- 通过指针算法访问结构数据成员
- 是否可以访问类数据成员并在析构函数中对它们执行操作?
- 如何在 c++ 中访问类的私有数据成员
- 现代C++编译器是否优化了对类中同一数据成员的重复访问?
- 无法访问派生类函数内的基类的受保护数据成员
- 我将如何访问类中结构的数据成员
- 访问嵌套结构的数据成员并将结构传递到功能C
- 使用静态成员函数访问静态数据成员
- 我正在尝试使用朋友功能,但我无法访问第二类的私人数据成员
- C 继承访问受保护的数据成员
- 为什么要检查静态数据成员的访问规范