#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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.