C++编程思想 第1卷 第15章 多态性和虚函数 运算符重载

就像对成员函数那样,我们可以使用virtual运算符

可能对两个不知道类型的对象进行操作,所以实现virtual运算符通常会很复杂

例如,对于一个处理矩阵,向量和标量的系统,三个成分都是派生自Math类

为了简单起见,这里仅重载了operator*
重载的目的是使任意两个Math对象相乘并且生成所需的结果
注意矩阵乘以向量和向量乘以矩阵是两个完全不同的操作

main()中的问题在于,表达式m1*m2包含了两个向上类型转换的Math引用,因此
不知道这两个对象的类型

//: C15:OperatorPolymorphism.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Polymorphism with overloaded operators
#include <iostream>
using namespace std;

class Matrix;
class Scalar;
class Vector;

class Math {
public:
  virtual Math& operator*(Math& rv) = 0;
  virtual Math& multiply(Matrix*) = 0;
  virtual Math& multiply(Scalar*) = 0;
  virtual Math& multiply(Vector*) = 0;
  virtual ~Math() {}
};

class Matrix : public Math {
public:
  Math& operator*(Math& rv) {
    return rv.multiply(this); // 2nd dispatch
  }
  Math& multiply(Matrix*) {
    cout << "Matrix * Matrix" << endl;
    return *this;
  }
  Math& multiply(Scalar*) {
    cout << "Scalar * Matrix" << endl;
    return *this;
  }
  Math& multiply(Vector*) {
    cout << "Vector * Matrix" << endl;
    return *this;
  }
};

class Scalar : public Math  {
public:
  Math& operator*(Math& rv) {
    return rv.multiply(this); // 2nd dispatch
  }
  Math& multiply(Matrix*) {
    cout << "Matrix * Scalar" << endl;
    return *this;
  }
  Math& multiply(Scalar*) {
    cout << "Scalar * Scalar" << endl;
    return *this;
  }
  Math& multiply(Vector*) {
    cout << "Vector * Scalar" << endl;
    return *this;
  }
};

class Vector : public Math  {
public:
  Math& operator*(Math& rv) {
    return rv.multiply(this); // 2nd dispatch
  }
  Math& multiply(Matrix*) {
    cout << "Matrix * Vector" << endl;
    return *this;
  }
  Math& multiply(Scalar*) {
    cout << "Scalar * Vector" << endl;
    return *this;
  }
  Math& multiply(Vector*) {
    cout << "Vector * Vector" << endl;
    return *this;
  }
};

int main() {
  Matrix m; Vector v; Scalar s;
  Math* math[] = { &m, &v, &s };
  for(int i = 0; i < 3; i++)
    for(int j = 0; j < 3; j++) {
      Math& m1 = *math[i];
      Math& m2 = *math[j];
      m1 * m2;
    }
    getchar();
} ///:~

输出
Matrix * Matrix
Matrix * Vector
Matrix * Scalar
Vector * Matrix
Vector * Vector
Vector * Scalar
Scalar * Matrix
Scalar * Vector
Scalar * Scalar

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81357370