在 The C++ Programming Language 一书的第 24.3.4 章中说
class Cfield : public Field{ /*...*/ }
This expresses the notion that a
Cfield
really is a kind of Field, allows notational convenience when writing aCfield
function that uses a member of the Field part of theCfield
, and - most importantly - allows aCfield
to override Field virtual functions. The snag is that theCfield*
toField*
conversion implied in the declaration ofCfield
defeats all attempts to control access to theField
:void g(Cfield* p) { *p = "asdf"; // access to Field controlled by Cfield's assignment operator: // p->Cfield::operator=("asdf") Field* q = p; // implicit Cfield* to Field* conversion *q = "asdf" // OOPS! no control }
我在这里不明白的是加粗的句子。 Cfield
如何阻止控制对 Field
的访问的尝试?
实际上,最后一行代码:
*q = "asdf";
将调用 Field::operator=("asdf")
,那么 Cfield
是如何阻止控制对 Field
的访问的呢?
最佳答案
CField
实例应该提供对 Field
的受控(即通过 CField::operator=()
以某种方式检查)访问基类数据。但是,如果您将 CField *
隐式转换为 Field *
,然后取消引用它,那么该控件就会消失,因为您选择了 Field::operator=( )
。
我同意这不是 BS 的著作中最清晰的,在我看来这有点无关紧要——只要你用心去做,你总是可以“不受控制地访问”任何东西。
关于c++ - 关于 C++ 编程语言的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6264264/