`在[模板类] [成员]的实例化中受到保护[。 。 。] [公共成员]无法访问'

时间:2014-08-08 19:23:26

标签: c++ templates inheritance

尝试实例化SystemBodyAcceleratedBody类时遇到以下错误:

error: 'bool InitializationChecker::is_initialized_' is protected

确实,is_initialized_ protected

class InitializationChecker {
 [. . .]
 protected:
  bool is_initialized_;
};

is_initialized_InitializationChecker通过其他几个类继承。

InitializationChecker
           ^
           |
MultipleInitializationChecker
  ^
  |
Body
  ^
  |
AcceleratedBody
     ^
     |
SystemBody

Body声明为:

template<typename Type> class Body : public MultipleInitializationChecker {
  using MultipleInitializationChecker::is_initialized_;
 public:
  Body() {
    this->is_initialized_ = false;
  }
  Body(const Scalar<Type> mass__,
       const CartesianVector<Type> position__,
       const CartesianVector<Type> velocity__)
      : mass_(mass__),
        position_(position__),
        velocity_(velocity__) {
          this->is_initialized_ = true;
  }
  [. . .]
  Scalar<Type> mass_;
  CartesianVector<Type> position_;
  CartesianVector<Type> velocity_;
};

我还遇到另一个问题:SystemBody的某些成员无法访问。例如:

error: 'Scalar<double> Body<double>::mass_' is inaccessible
当我尝试执行以下操作时输出

SystemBody<double> system_body;
std::cout << system_body.mass_.value();

即使SystemBody只添加了一个不相关的私有成员,AcceleratedBody也是如此声明:

template<typename Type> class AcceleratedBody : public Body<Type> {
  using Body<Type>::is_initialized_;
  using Body<Type>::mass_;
  using Body<Type>::position_;
  using Body<Type>::velocity_;
 public:
  AcceleratedBody() : Body<Type>::Body() {}
  AcceleratedBody(const Scalar<Type> mass__,
                  const CartesianVector<Type> position__,
                  const CartesianVector<Type> velocity__,
                  const CartesianVector<Type> acceleration__)
      : Body<Type>::Body(mass__, position__, velocity__),
        acceleration_(acceleration__) {}
  [. . .]
  CartesianVector<Type> acceleration_;
};

请注意,mass_position_velocity_都已在Body公开宣布。

1 个答案:

答案 0 :(得分:0)

using MultipleInitializationChecker::is_initialized_;在类的私有区域中执行此操作会使其成为私有区域。你甚至不需要那条线。你觉得它做什么?