操作符重载函数都是虚汗函数?
如题,本人教材中没看到过如此说法,但被面试官这么一问,不敢确信啊,请朋友们帮忙指点。。。这里先谢了!
[解决办法]
假的,骗你呢
你被吓到了
[解决办法]
操作符重载函数,通常不是虚函数,当然用虚函数也木有问题。
[解决办法]
完全可以理直气壮地告诉他:不是。因为操作符重载是基于类的,例如如果为类A重载了[]操作符,只代表A类型的变量才会如此使用:a[i](假设已经提前定义A a并初始化),这个函数根本不具备虚函数那种在类间的传递性。但是很奇怪,在C++里你却可以把重载操作符的成员函数定义为虚的,问题是在子类对象中这种函数压根不能用,有高人能否给个解释?
比如:
- C/C++ code
#include<iostream>#include<cassert>using namespace std;class A{public: int len; int* data;public: A(){} A(int l) { len=l; data=new int[len]; } ~A() { delete [] data; }virtual int& operator[](int index) { assert(index>=0&&index<len); return data[index]; }virtual const int& operator[](int index) const { assert(index>=0&&index<len); return data[index]; } };class B:public A{};int main(){ A a(10); for(int i=0;i<10;++i) { a[i]=i; } cout<<a[3]<<endl; system("pause"); return 0;}
[解决办法]
[解决办法]