复制赋值函数如何访问另一个对象的私有成员(Stroustrup 原则与实践书)?
How is the copy assignment function accessing private members of the other object (Stroustroup Principles and Practice book)?
我一直在阅读 "Programming: Principles and Practice using C++, 2nd Edition" 的第 18.3.2 章,其中描述了向量复制赋值操作。这是书中提出的想法:
class vector {
int sz;
double* elem;
public:
vector& operator=(const vector&) ; // copy assignment
// . . .
};
根据此 class 定义 int sz
和 double* elem
是 vector
class.
的私有成员
现在复制分配定义为:
vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
double* p = new double[a.sz]; // allocate new space
copy(a.elem,a.elem+a.sz,elem); // copy elements
delete[] elem; // deallocate old space
elem = p; // now we can reset elem
sz = a.sz;
return *this; // return a self-reference
}
我的理解是:a
作为 const vector&
传递给重载的 operator=
函数。但是在定义的第二行中,对 std::copy()
的调用能够以某种方式访问 a.elem
和 a.sz
,据我所知,它们是 a
引用的对象的私有成员.我只是不明白这怎么可能。
我在这里错过了什么?提前感谢您的回答!
访问控制是针对每个 class,而不是针对每个实例:A
的任何成员都可以访问类型 A
的任何对象的任何成员。有一个例外,派生 class 的成员只能通过派生类型的对象(或通过该类型本身进行静态成员访问)访问基 class 的 protected
成员.
我一直在阅读 "Programming: Principles and Practice using C++, 2nd Edition" 的第 18.3.2 章,其中描述了向量复制赋值操作。这是书中提出的想法:
class vector {
int sz;
double* elem;
public:
vector& operator=(const vector&) ; // copy assignment
// . . .
};
根据此 class 定义 int sz
和 double* elem
是 vector
class.
现在复制分配定义为:
vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
double* p = new double[a.sz]; // allocate new space
copy(a.elem,a.elem+a.sz,elem); // copy elements
delete[] elem; // deallocate old space
elem = p; // now we can reset elem
sz = a.sz;
return *this; // return a self-reference
}
我的理解是:a
作为 const vector&
传递给重载的 operator=
函数。但是在定义的第二行中,对 std::copy()
的调用能够以某种方式访问 a.elem
和 a.sz
,据我所知,它们是 a
引用的对象的私有成员.我只是不明白这怎么可能。
我在这里错过了什么?提前感谢您的回答!
访问控制是针对每个 class,而不是针对每个实例:A
的任何成员都可以访问类型 A
的任何对象的任何成员。有一个例外,派生 class 的成员只能通过派生类型的对象(或通过该类型本身进行静态成员访问)访问基 class 的 protected
成员.