//多态性
//从派生类到基类的转换
//引用或者指针既可以指向基类对象,也可以指向派生类对象
//只有通过引用或者指针调用虚函数才会发生动态绑定。
//为什么定义虚的函数?可以重新定义。只有虚函数才可以重写,(基类或者派生类里面)
动态绑定的方法,执行出来的效果,就是多态
#include <iostream>//txwtech-202001
#include <string>//多态,动态绑定
using namespace std;//导入名称空间
class Animal
{
//成员略
};
class Dog :public Animal
{
//成员略
};
class Cat :public Animal
{
};
class Item_base
{
public:
//int x;
Item_base(const std::string &book = "",
double sales_price = 0.0) :isbn(book), price(sales_price) {}//构造函数
std::string book() const
{
return isbn;
}
virtual double net_price(size_t n) const//为什么定义虚的函数?可以重新定义。只有虚函数才可以重写
{
return n * price;
}
private://类的内部使用
std::string isbn;
protected://专门用来做继承用的
double price;
};
class Bulk_item :public Item_base
{
public:
Bulk_item(const std::string &book = "", double sales_price = 0.0,
size_t qty = 0, double disc_rate = 0.0) :
Item_base(book, sales_price), min_qty(qty), discount(disc_rate) {}
void test()
{
//cout << x << endl;
cout << price << endl;
//cout << isbn << endl;
}
void test2(const Bulk_item &d, const Item_base &b)
{
//cout << d.x << endl;
cout << d.price << endl;
//cout << b.x << endl;
//cout << b.price << endl;
}
double net_price(size_t cnt) const//继承函数时,这里可以重定义,继承函数
{
if (cnt >= min_qty)
return cnt * (1 - discount)*price;
else
return cnt * price;
}
private:
size_t min_qty;
double discount;
};
//做一个函数
void print_total(ostream &os, Item_base *item, size_t n)
{
os << "ISBN: " << item->book() << "\t number sold: " << n << "\ttotal price: " << item->net_price(n) << endl;
//item->net_price(n)代码就是多态的
}
int main()
{
//Animal a;
//Dog d;
//Cat c;
//Item_base item("0-12-3456-789", 9.9);
//cout << item.book() << ": " << item.net_price(10) << endl;
cout << item.x << endl;
///*cout << item.isbn << endl;
//cout << item.price << endl;*/
cout << "hello111" << endl;
//Bulk_item item2("0-12-3456-789", 9.9, 10, 0.12);
cout << item2.x << endl;
//cout << item2.book() << ": " << item2.net_price(10) << endl;
//item2.test();
//item2.test2(item2, item);
//多态,动态绑定的实现
Item_base* a = new Item_base("1-234-567-01",11.0);
Bulk_item* b = new Bulk_item("1-234-567-02",22.0,2,0.05);//指向子类对象的指针
print_total(cout,a,2);
print_total(cout,b,3);
Item_base* books[5];//指针数组,5个指针
books[0] = new Item_base("0-123-456-01",10.0);//new 创建基类对象
books[1] = new Bulk_item("0-123-456-01", 20.0,6,0.05);//new 也可以指向派生类对象
books[2] = new Item_base("0-123-456-03", 30.0);//new 创建基类对象
books[3] = new Bulk_item("0-123-456-04", 40.0, 4, 0.15);//new 也可以指向派生类对象
books[4] = new Bulk_item("0-123-456-05", 50.0, 2, 0.18);//new 也可以指向派生类对象
int num[5];
num[0] = 2;
num[1] = 10;
num[2] = 1;
num[3] = 5;
num[4] = 3;
for (int i = 0; i < 5; i++)
{
print_total(cout,books[i],num[i]);
//动态绑定的方法,执行出来的效果,就是多态
//根据指针所指向的对象不同,指向不同的对象,对象去调用不同的虚函数。有可能是基类,有可能是
//派生类的。
}
//分别调用基类的netprice与派生类的Netprice. netprice就是多态,根据对象决定(基类不打折,派生类打折)
//比如飞机在飞,鸟儿也在非,不同的飞
getchar();
return 0;
//多态性
//从派生类到基类的转换
//引用或者指针既可以指向基类对象,也可以指向派生类对象
//只有通过引用或者指针调用虚函数才会发生动态绑定。
//为什么定义虚的函数?可以重新定义。只有虚函数才可以重写,(基类或者派生类里面)
}