#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); // 二次指派,
}
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
{
Math& operator*(Math& rv)
{
return rv.multiply(this);
}
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
{
Math& operator*(Math& rv)
{
return rv.multiply(this);
}
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;
}
};
class Pet
{
public:
virtual ~Pet(){}
};
class Dog : public Pet{};
class Cat : public Pet{};
class Shape
{
public :
virtual ~Shape(){}
};
class Circle : public Shape{};
class Square : public Shape{};
class other {};
int main()
{
Circle c;
Shape* sh = &c; // 向上类型转换,
sh = static_cast<Shape*> (&c); // 这个是静态的向上类型转换,
Circle* cp = 0;
Square* sp = 0;
//cout << typeid(*sh).name() << endl;
if (strcmp(typeid(*sh).name(),"class Circle") == 0) // strcmp 是显示字符串,
cp = static_cast<Circle*>(sh); // 向下类型转换,
if (strcmp(typeid(*sh).name(), "class Square") == 0)
sp = static_cast<Square*>(sh);
if (cp != 0)
cout << "It's a Circle ! " << endl;
if (sp != 0)
cout << "It's a Square ! " << endl;
Pet* b = new Cat;
Cat* d1 = dynamic_cast<Cat*> (b); // 动态的向下类型转换,dynamic_cast执行的时候速度会慢一些,
Dog* d2 = dynamic_cast<Dog*> (b); // 这是一个错误的向下类型转换,
cout << " d1 = " << (long)d1 << endl;
cout << " d2 = " << (long)d2 << endl; // d2 = 0, 0 指针
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;
}
return 0;
}
多态与虚函数 4
最新推荐文章于 2024-07-26 22:51:51 发布