c++ - 无法访问派生类中的 protected 类成员

标签 c++ inheritance protected access-specifier

错误是:

d_start is a protected member of CourseActivity
duration is a protected member of CourseActivity
location is a protected member of CourseActivity

class CourseActivity{

protected:
    StartTime* d_start;
    double duration;
    std::string location;

public:
    CourseActivity() = default;
    CourseActivity(const StartTime* _start, double _duration,
                   const std::string_location);
    void reschedule(StartTime* _newStart);
    void print() const;

}; 



class Lecture: public CourseActivity{
    std::string topic;
    bool deflt = false; //indicate which constructor was used.
                        //false = 1st. true = 2nd

public:
    Lecture(const StartTime* _start, double _duration,
            const std::string location, const std::string& _topic);
    Lecture(const CourseActivity& _oActivity, const std::string& topic );
    void print();
};

// ERROR
Lecture::Lecture(const CourseActivity& _oActivity, const std::string& _topic)
: CourseActivity(_oActivity.d_start,_oActivity.duration,_oActivity.location){
    topic = _topic;
    deflt = true;
}
// ERROR 

最佳答案

您正在将 CourseActivity 的实例传递给函数 Lecture::Lecture。即使 CourseActivity 确实是 Lecture 的基类,您也无法从外部访问 protected 类成员(如 _oActivity.duration),即使您正在操作的对象属于派生类型。

为避免您的特殊问题,您可以在基类中创建此构造函数

CourseActivity::CourseActivity(const CourseActivity &_oActivity)

并调用它

Lecture::Lecture(const CourseActivity& _oActivity, const std::string& _topic)
    : CourseActivity(_oActivity)

在派生类中。在基类中,您可以访问 protected 成员,而在派生类中则不允许这样做。

关于c++ - 无法访问派生类中的 protected 类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351721/

相关文章:

c++ - 字符中的奇怪字符

c++ - 防止派生类从基类隐藏非虚函数

inheritance - 在 SCSS 中包含另一个类

C++ 继承 : protected variables not available

c++ - Bison 和 rec2c : Get Current line number

c++ - 按位与等于 0 的整数对

c++ - 在 C++ 中连接 .wav 文件

javascript - 原型(prototype)继承和实例数组的问题

c++ - 使用 protected 或公共(public)的虚拟函数?

c++ - 访问 protected 方法的方法指针?