//29CppPrimer_转换与继承-txwtech-15.04
//#include <iostream>
//using namespace std;
派生类->基类
--引用转换/指针转换。才能够实现多态,动态绑定--c++重点
--对象转换--不能实现多态与动态绑定
//
*基类->派生类
--基类到派生类的自动转换不存在
--强制转换 --一般不用,很少用
//
//29CppPrimer_转换与继承-txwtech-15.04
//#include <iostream>
//using namespace std;
派生类->基类
--引用转换/指针转换。才能够实现多态,动态绑定--c++重点
--对象转换--不能实现多态与动态绑定
//
*基类->派生类
--基类到派生类的自动转换不存在
--强制转换 --一般不用,很少用
//
//int main()
//{
//
// getchar();
// return 0;
//}
#include <iostream>//txwtech-引用CC25a_demo
#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.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;
};
//new added --转换与继承^^^txwtech20200115
void print_total_1(ostream &os, const Item_base item, size_t n) //对象转换-没有发挥打折作用
{
os << "ISBN: " << item.book() << "\tnumber sold: " << n << "\ttotal price: " << item.net_price(n) << endl;
}
void print_total_2(ostream &os, const Item_base *item, size_t n)//指针转换
{
os << "ISBN: " << item->book() << "\tnumber sold: " << n << "\ttotal price: " << item->net_price(n) << endl;
}
void print_total_3(ostream &os, const Item_base &item, size_t n)//引用转换
{
os << "ISBN: " << item.book() << "\tnumber sold: " << n << "\ttotal price: " << item.net_price(n) << endl;
}
new added --转换与继承^^^txwtech20200115
int main()
{
Animal a;
Dog d;
Cat c;
Item_base item("0-12-3456-789", 9.9);//基类
Bulk_item item2("0-12-3456-789", 9.9, 10, 0.12);//派生类
print_total_1(cout,item,10);
print_total_1(cout, item2, 10);//对象转换,派生转基类,调用基类。转换有问题,应该打折
cout << endl;
print_total_2(cout, &item, 10);//指针,传地址
print_total_2(cout, &item2, 10);//传派生类对象。指针转换.这个就打折了。
print_total_3(cout, item, 10);//传基类
print_total_3(cout, item2, 10);//传派生类,引用转换。这个就打折了。
item = item2;//小子给老子
//item2 = item;//不能老子赋值给小子,
//Bulk_item *p = &item;//指针也不行
//对象不能强制转换,只能指针与引用。-很少做。一般不做。
Bulk_item *p = static_cast<Bulk_item *>(&item);//强制转换-老子赋值给小子。做法很危险
cout << p->net_price(10) << endl;
getchar();
return 0;
}