首页 > 解决方案 > 如何在 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。这里有什么解决办法。

标签: c++operator-overloadingthisprotectedderived-class

解决方案


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

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

推荐阅读