在 C++ 中实现复制控制时如何处理基 class 的私有成员?

How to handle private members of a base class when implementing copy control in C++?

给定一个派生自 Faculty class 的 Teacher class,我将如何处理 Teacher 对象的名称,该对象在 Faculty 中定义为私有成员,但在 Teacher 中不是,因为复制控制?

// example code for the two classes
class Faculty{
public:
/* constructor

   copy constructor

   destructor

   assignment operator
*/

string get_name() const{
return name;

private:
string name;
};

class Teacher : public Faculty{};

假设 Faculty class 有一个有效的复制控制

// Copy constructor
Teacher(const Teacher& rhs) : Faculty(rhs){
     name = rhs.name; 
}

此行未编译,因为它试图访问 Faculty 的私有成员。此行是否需要,或者副本的名称是否已由初始化列表 Faculty(rhs) 设置为 rhs.name?如果直接在Teacher的私有域中定义一个字符串name是否可以访问?

// Assignment operator
Teacher& operator=(const Teacher& rhs){
     Faculty::operator=(rhs);
     if(this != &rhs){
          name = rhs.name; // same issue 
     }
     return *this;
}

与复制控制相同的问题,这是否需要,或者名称是否已被 Faculty class 的赋值运算符更改为 rhs.name?

Is this line needed or is the name of the copy already set to rhs.name by the initialization list, Faculty(rhs)?

不需要该行(假设默认或正确实现 Faculty 复制构造函数)。 Faculty 构造函数将为您正确分配或初始化 name

Would name be accessible if I directly define a string name in the private field of Teacher?

是的,有点。但它将是 name 的一个完全独立的实例。你不想这样做。您只想 name 定义一次。