- C++中虚操作符和其他虚函数的规则一样,操作符可以为虚函数,进行动态绑定, 虽然这种情况并不多见。本文以赋值操作符operator=举例。
- 派生类中要重定义基类虚函数,要注意参数必须为基类引用类型,否则与基类中虚函数是完全不同的,无法进行预期的动态绑定。
- 派生类除了重定义基类的虚操作符,还要定义自身的操作符重载。即派生层次每增加一层,理论上派生类就需要多定义一个操作符重载。
以下程序使用引用reference,通过指针调用赋值操作符(例:*p = value)情况是一样的。
- #include <iostream>
- using namespace std;
-
- class Base
- {
- public:
- virtual Base& operator=(const Base& rhs)
- {
- cout << "Base" << endl;
- return *this;
- }
- };
-
- class Derived : public Base
- {
- public:
-
-
- Derived& operator=(const Derived& rhs)
- {
- cout << "Derived_D" << endl;
- return *this;
- }
-
-
-
- virtual Derived& operator=(const Base& rhs)
- {
- cout << "Derived_B" << endl;
- return *this;
- }
- };
-
- class Derived2 : public Derived
- {
-
-
-
-
- };
-
- int main()
- {
- Base b1, b2;
- Derived d1, d2;
-
- Derived &rd = d1;
-
- Base &rb1 = b1;
- Base &rb2 = d2;
-
- rb1 = d1;
- rb2 = d2;
-
- rb1 = rb2;
- rb2 = rb1;
-
- rd = d1;
- rd = b1;
-
- getchar();
- return 0;
- }