如何在 C++ 中访问受保护的运算符成员

问题描述

如何在 C++ 中访问受保护的运算符成员

class A {
   char* m="ABCD";
  protected:
   const char& operator[](int i)const{ return m[i]; };
public:
A();
};

class B : Public A {
   char* D;
  Public:
B():A(){};
void display(){  ///////////what should I do here   }
};

如果我有这个代码,并且我想在派生类中使用运算符[],例如我需要在派生类的显示显示[0]=A。这里有什么解决方案。

解决方法

您可以从成员函数中取消引用此 this 对象并使用 [] 运算符,即:

void display(){  std::cout << (*this)[1];  }