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

Why I am getting access to other class' private members?

本文关键字:成员 我可以 访问 其他 为什么      更新时间:2023-10-16
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 来访问其他班级的私人成员。但事实证明,如果我从另一个类调用它,它不再需要这些 getter,我可以直接访问它们。但这在该类之外是不可能的。

Complex result = first + second;

这将为 Complex 类调用 operator+,运算符本身是 Complex 类的一部分,因此它可以访问该类的所有成员,即使对于作为参数传递other实例也是如此。

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

运算符<<没有为您的类定义,因此您必须将"可打印的内容"传递给 Cout 的<<运算符。您不能简单地编写result.real,因为它在此上下文中是私有的,即Complex类之外。

它不是另一个类;它是另一个实例A中的函数可以访问另一个Aprivate的成员。这就是它的工作原理。否则就不可能做像你这样的事情,我们需要能够做这些事情。

相关文章: