传递对象的c ++私有变量

c++ private variable of a passed object

#include <stdio.h>

class HelloClass
{
    float t;
public:
    HelloClass(float x) : t(x) {};
    float Add(HelloClass a);
};

float HelloClass::Add(HelloClass b)
{
    return t + b.t; // How is b.t accessible here?
}

int main()
{
    HelloClass a(2), b(3);
    printf("hello %f\n", a.Add(b));
    return 0;
}

您好,上面的代码编译通过了。但是我无法理解 b.t 是如何访问的?有人可以阐明这一点吗?

这是预期的行为,private members 成员函数可以访问,即使它们来自其他实例。

(强调我的)

A private member of a class is only accessible to the members and friends of that class, regardless of whether the members are on the same or different instances:

class S {
  private:
    int n; // S::n is private
  public:
    S() : n(10) {}                    // this->n is accessible in S::S
    S(const S& other) : n(other.n) {} // other.n is accessible in S::S
};