首页 > 解决方案 > 为什么我可以访问其他班级的私人成员?

问题描述

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

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

标签: c++classprivate

解决方案


 Complex result = first + second;

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

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

operator<< 没有为您的班级定义,因此您必须将“可打印的东西”传递给 cout 的 << 运算符。您不能简单地编写result.real,因为它在这种情况下是私有的,即在Complex课堂之外。


推荐阅读