How can a derived class use a protected member of the base class?

前端 未结 2 994
礼貌的吻别
礼貌的吻别 2020-12-21 03:49

Say that a base class A defines a protected member. A derived class B uses this member.

class A
{
public:
  A(int v) : value(v) { }         


        
2条回答
  •  情歌与酒
    2020-12-21 04:30

    There is actually a loophole using member pointers (no casting, no copying):

    void B::compare_and_print(const A& other) const
    {
      auto max_value = std::max(value, other.*(&B::value));
      std::cout << "Max value: " << max_value << "\n";
    }
    

提交回复
热议问题