Inheritance/Polymorphism - 我是否被迫使用 "protected" 变量?

Inheritance/Polymorphism - Am I forced to use "protected" variables?

我目前正在使用 Big C++ 第 2 版,使用 Code::Blocks 17.12,关于继承的章节

本书介绍了受保护的变量类型,适用于您希望允许派生 class 访问所述变量的情况。

这本书还预先警告说,受保护的元素会遭受 public 变量的一些陷阱:在最坏的情况下,派生的 class 成员可能会破坏基础 class 数据

这本书在他们介绍这个的专门部分中演示了时钟程序中受保护成员的使用,但在最终代码中他们最终将变量设置为私有,然后使用一些 get_ 辅助函数来访问此私人数据。这种私有和使用辅助函数的组合总是在我的 IDE 中返回错误,我无法解决这个问题

以我为 P8.1 创建的这个简单示例为例,它是程序员的员工记录,员工基础 class 和程序员派生 class。我创建了以下 ctor,变量名称和 sal 在基础 class

中设置为 protected 状态
Programmer::Programmer(string p_name, double p_sal)
    :Employee(get_name(), get_sal())
{
    name=p_name;
    sal=p_sal;
}

使用这段代码,程序可以完美运行。

根据教科书,如果变量name和sal在base中设置为private状态,那么我应该也可以执行代码,当然我是使用我创建的 get_ 辅助函数来访问数据。

谁能解释一下这里的问题是什么?我应该接受使用 protected 还是真的有办法让我的所有变量在 classes 期间保持私有?

我也在 https://docs.microsoft.com/en-us/cpp/cpp/protected-cpp?view=vs-2019

上找到了这个

Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.

到目前为止我还没有涉及到静态,所以我最终尝试了一堆不同的指针和引用组合,none 两者都有效。

我基本上想了解什么时候使用 protected 什么时候使用 private,而这本书对此并不清楚。有什么想法吗?

出于某种原因,我认为在调用基本 class 构造函数时,您需要提供辅助函数来访问私有数据。

因为基本构造器已经是 public,通过向它提供派生 class 构造器的参数,它将正确构造派生的 class obj,允许 get_func 读取它的私有变量

Programmer::Programmer(string p_name, double p_sal)
    :Employee(p_name, p_sal)
{}

书上没看明白,谢谢大家帮忙解惑