c++ - 为什么我可以访问其他班级的私人成员?
问题描述
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,我可以直接访问它们。但这在该课程之外是不可能的。
解决方案
Complex result = first + second;
这为 Complex 类调用 operator+,operator 本身是 Complex 类的一部分,因此它可以访问该类的所有成员,甚至other
例如作为参数传递。
std::cout << result.getReal() << " + " << result.getImaginary() << "i";
operator<< 没有为您的班级定义,因此您必须将“可打印的东西”传递给 cout 的 << 运算符。您不能简单地编写result.real
,因为它在这种情况下是私有的,即在Complex
课堂之外。
推荐阅读
- docker - 鉴于服务器 URL 的主机名不完全限定,如何在 OpenAM 中创建 Web 策略代理?
- c# - 可从代码访问的 C# 构建时间可设置值
- javascript - 我怎样才能在时间属性中获得现在的时间?
- angularjs - 如何让我的 webapp 只使用 https 协议?
- c - 用 C 文件打开代码。我需要解释为什么这段代码在多次运行时会给出不同的输出
- python-3.x - 如何创建列表并从另一个数据框中过滤掉行?
- sql - SQL IF/ELSE 中的条件语句
- vba - 如何在电子邮件正文中添加文本?
- c++ - 输入两个 3*3 矩阵并显示矩阵的和和乘积的 C++ 程序
- reactjs - TypeError:props.onDateTimeUpdate 不是函数