为什么我可以访问其他班级的私人成员?
Why I am getting access to other class' private members?
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
中的函数可以访问另一个A
private
的成员。这就是它的工作原理。否则就不可能做像你这样的事情,我们需要能够做这些事情。
相关文章:
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 我可以在此模板中删除此类成员吗?
- 为什么我可以访问其他班级的私人成员?
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 我可以使用在类构造函数中初始化的流类型的成员变量吗?
- 我可以说服自动生成的构造函数将我的 POD 类成员归零吗?
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 无法在clang Linux中分配非静态成员函数,但我可以在Visual Studio Windows中分配
- 为什么我可以调用一个从const方法更改成员的方法
- 我可以在初始化之前使用 std::array 成员变量中的 data() 指针吗?发出警告
- 当使用指定的初始值设定项时,我可以强制用户为成员提供值吗
- 为什么我可以通过SubBase类的公共继承方法打印出基类的私人继承成员
- 为什么我可以通过野生指针调用成员函数
- C++ 入门 12.1:我可以在类中使用静态向量成员实现 StrBlob<string> 吗?
- 在成员初始化列表中,我可以创建对列表中不在列表中的成员变量的引用
- 我可以使用Priority_queue的基础容器的成员功能
- 我可以使用std :: bind将指针转换为成员函数的指针转换为函数的指针
- C :我可以将成员变量的迭代器带入班级之一
- 我们如何将Ostream函数作为类的成员函数实现,而不是作为朋友函数,以便我可以用作虚拟函数