在The C++ Programming Language一书中,作者声称,对于下面的类设计,
class complex{
double re, im;
public:
double real( ) const { return re;}
double imag( ) const { return im;}
};
Given real() and imag(), we can define all kinds of useful operators without granting them direct access to the representation of complex.
如何理解这个说法?哪些地方需要直接访问,哪些地方需要间接访问?
作者还举了下面的例子。
inline bool operator==(complex a, complex b)
{
return a.real( )==b.real() && a.imag () ==b.imag( );
}
这个给定的例子与作者在上面给出的陈述有什么关系。
最佳答案
作者这里所说的就是所谓的“封装”。定义“==”的新函数定义了比较新类型(复数)的两个对象的逻辑,而不必知道复数的内部实际上是什么样子。
你的问题真的很含糊,所以我认为你想做的是更多地了解“面向对象编程”和“封装”。在谷歌上搜索这些术语应该会有帮助。
事实上,this可能是一个很好的起点。
关于c++ - Complex类的成员函数设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5234382/