我想要一个可以继承并覆盖为 [] 运算符创建值的函数的类。为什么这些没有相同的结果?有没有办法在不使用指针的情况下获得第二个结果?
代码:
#include <iostream>
using std::cout;
class session {
public:
session(){}
~session(){}
void operator[](const char* c) {foo(c);}
protected:
virtual void foo(const char* c) {cout << "parent called" << "\n";}
};
class session2 : public session {
public:
session2(){}
~session2(){}
protected:
virtual void foo(const char* c) {cout << c << "\n";}
};
int main() {
session2 s2;
session a = s2;
a["child called"];
session* b = &s2;
(*b)["child called"];
return 0;
}
输出:
parent called
child called