c++ - 关于 C++ 编程语言的问题

标签 c++ inheritance

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 a Cfield function that uses a member of the Field part of the Cfield, and - most importantly - allows a Cfield to override Field virtual functions. The snag is that the Cfield* to Field* conversion implied in the declaration of Cfield defeats all attempts to control access to the Field:

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/

相关文章:

c++ - 在默认构造函数中声明 arr 时未在此范围内声明“arr”

Python 多重继承单元测试 -

java - 为什么继承的公共(public)方法操作父类(super class)的私有(private)属性而不是子类?

c++ - 对象在内存中是什么样子的?

c# - 获取窗口的投影尺寸

c++ - 没有运算符 "<"匹配这些操作数操作数类型是 : double < my_class

c++ - 为什么使用声明不能解决菱形继承(钻石问题)?

c++ - 为什么我在 ‘]’ token 之前得到数组绑定(bind)不是整数常量,即使全局声明了大小?

具有继承的 C++ 范围解析用法

c# - 实现接口(interface)但返回返回类型的子类?