【发布时间】:2021-12-11 08:58:00
【问题描述】:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Test {
public:
int testing() {
Test t;
return t.x;
}
private:
int x = 0;
};
int main() {
Test a;
cout << a.testing() << endl;
}
我不知道我可以在Test 的类定义中访问t 的私有数据成员x(Test 的实例不是this)。为什么我可以在示例代码中使用t.x?
【问题讨论】:
-
如果你不能访问班级内的私人数据,你怎么能访问它呢?
-
编写比较运算符或移动构造函数/赋值时非常重要
-
你在问为什么你可以从
a对象访问t.x?或者为什么你可以从方法中访问private成员?前者见With a private modifier, why can the member in other objects be accessed directly? -
“我不知道” 好吧,你为什么知道还有
private:或class这样的东西呢? 那个来源告诉你什么它是如何工作的? “为什么我可以在下面的代码中使用“t.x”?那么,你认为应该可以在 anywhere 使用t.x吗?如果不是,那么首先拥有int x = 0;有什么意义?您希望代码看起来如何,从而导致该值发生变化?拥有无法使用的数据有什么意义? -
Test的任何实例都可以查看和操作任何其他Test实例的所有数据,它可以得到它肮脏的手指。