为什么我可以访问其他班级的私人成员?

时间:2020-01-10 13:59:40

标签: c++ class private

class Complex
{
private:
    float real, imaginary;
public:
    Complex(float real, float imaginary)
    {
        this->real = real;
        this->imaginary = imaginary;
    }
    float getReal() const
    {
        return this->real;
    }
    float getImaginary() const
    {
        return this->imaginary;
    }
    Complex operator+(Complex other)
    {
        return Complex(this->real + other.real, this->imaginary + other.imaginary); // Here I can access other class' private member without using getter methods.
    }
};

int main()
{
    Complex first(5, 2);
    Complex second(7, 12);
    Complex result = first + second; // No error
    std::cout << result.getReal() << " + " << result.getImaginary() << "i"; // But here I have to use getters in order to access those members.
    return 0;
}

为什么我可以从另一个班级访问班级的私人成员?我以为我必须使用吸气剂来访问其他班级的私人成员。但是事实证明,如果我从另一个类中调用它,则不再需要这些获取器,并且可以直接访问它们。但这在该类之外是不可能的。

2 个答案:

答案 0 :(得分:2)

 Complex result = first + second;

这将为Complex类调用operator +,operator本身是Complex类的一部分,因此它甚至可以访问作为参数传递的other实例的此类的所有成员。

std::cout << result.getReal() << " + " << result.getImaginary() << "i";

operator <<没有为您的课程定义,因此您必须将'something printable'传递给cout的<<运算符。您不能简单地编写result.real,因为它在此上下文中是私有的,即在Complex类之外。

答案 1 :(得分:2)

这不是另一堂课;这是另一个 instance ,并且A中的函数可以访问另一个private的{​​{1}}成员。这就是它的工作原理。否则,将不可能像您一样做事,而我们需要能够做那些事。