///15_3 运算符重载\\\gy%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
class quote
{
public:
quote() = default;
quote(string _bookNo, double _price) :bookNo(_bookNo),price(_price) {};
string isbn() { return bookNo; }
virtual double fin_price(size_t n)
{
return n*price;
};
protected:
double price;
private:
string bookNo;
};
//派生类可以访问基类的共有和受保护成员:受保护成员其他类不能访问,只有基类的派生类能访问
//派生类的作用域嵌套在基类的作用域内
class bulk_quote:public quote
{
public:
bulk_quote() = default;
bulk_quote(string _bookNo, double _price, size_t _min_n,double _sales):
quote(_bookNo, _price) ,min_n(_min_n),sales(_sales) {};
//price是基类有的成员数据,在继承类中还要传递参数吗?还是只初始化基类中新定义的成员数据?
//答:基类中的成员在基类中初始化,在派生类中quote(_bookNo, _price)
double fin_price(size_t n) override;//override的话形参列表要与基类的一样,否则可以不一样
//继承类的fin_price函数的参数列表和基类中fin_price的参数列表一样,怎样判断调用基类的还是继承类的fin_price?:看主函数
private:
size_t min_n;
double sales;
};
double bulk_quote::fin_price(size_t _n)
{
size_t n = _n;
if (n>=min_n)
{
return n*price*sales;
}
else
{
return n*price;
}
}
void main()
{
string s_quote = "ta";
string s_bulk_quote ="wo";
quote my_quote(s_quote,19);
bulk_quote my_bulk_quote(s_bulk_quote,20,10,0.5);
cout << my_quote.isbn() << endl;
cout << my_bulk_quote.isbn() << endl;//继承基类
cout << my_quote.fin_price(15) << endl;//调用基类
cout << my_bulk_quote.fin_price(15) << endl;//调用继承类
system("pause");
}
防止继承发生时,在定义类名时,类明后加final:
class NoDerived final {/* */};