首页 > 解决方案 > c++ 传递对象的私有变量

问题描述

#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访问?有人可以对此有所了解吗?

标签: c++private

解决方案


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

(强调我的)

一个private类的成员只能由该类的成员和朋友访问,无论成员是在相同的还是不同的实例上

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
};

推荐阅读