c/c++ 继承与多态 容器与继承1
程序员文章站
2023-04-05 17:11:52
问题:类B公有继承类A,类A有虚函数fun,类B覆盖了虚函数fun,有一个std::vector\,添加A的对象a,和B的对象b,到这个容器里,然后从vector里取出来,使用对象a.fun(),和对象b.fun(),会发生什么? 发现对象b.fun()的调用,实际调用的是父类A的fun()方法。也 ......
问题:类b公有继承类a,类a有虚函数fun,类b覆盖了虚函数fun,有一个std::vector<a>,添加a的对象a,和b的对象b,到这个容器里,然后从vector里取出来,使用对象a.fun(),和对象b.fun(),会发生什么?
发现对象b.fun()的调用,实际调用的是父类a的fun()方法。也就是子类部分被切掉了。
如何解决呢,用std::vector<a*>或者std::vector<std::shared_ptr<a>> ,但推荐用智能指针。
quote3.h
#ifndef __quote3_h__ #define __quote3_h__ #include <iostream> #include <memory> class quote{ public: quote() = default; quote(const std::string& book, double pri) :bookno(book), price(pri){} std::string isbn() const{return bookno;} virtual double net_price(std::size_t n)const{ return n * price; } virtual void debug()const{ std::cout << bookno << " " << price << std::endl; } virtual ~quote() = default; private: std::string bookno; protected: double price = 0.0; }; class disc_quote : public quote{ public: disc_quote() = default; disc_quote(const std::string& book, double price, std::size_t qyn, double disc):quote(book, price), quantity(qyn), discount(disc){} double net_price(std::size_t) const override = 0; protected: std::size_t quantity = 0;//折扣适用的数量 double discount = 0.0; //折扣率 }; class bulk_quote : public disc_quote{ public: bulk_quote() = default; bulk_quote(const std::string& book, double price, std::size_t qyn, double disc) :disc_quote(book, price, qyn, disc){} double net_price(std::size_t) const override; }; class min_quote : public disc_quote{ public: min_quote() = default; min_quote(const std::string& book, double price, std::size_t qyn, double disc) :disc_quote(book, price, qyn, disc){} double net_price(std::size_t) const override; }; #endif
quote3.cpp
#include "quote3.h" double bulk_quote::net_price(std::size_t cnt) const{ if(cnt >= quantity){ return cnt * (1 - discount) * price; } else{ return cnt * price; } } double min_quote::net_price(std::size_t cnt) const{ if(cnt < quantity){ return cnt * (1 - discount) * price; } else{ return cnt * price; } }
main.cpp
#include "quote3.h" #include <vector> double print_total(std::ostream& os, const quote& item, size_t n){ double ret = item.net_price(n); os << "isbn: " << item.isbn() << " # sold: " << n << " total due: " << ret << std::endl; return ret; } int main(){ std::vector<quote> qv; for(unsigned i = 0; i != 10; ++i){ qv.push_back(bulk_quote("01", 100, 10, 0.1)); } double total = 0; for(const auto s : qv){ total += s.net_price(20); } std::cout << total << std::endl; std::cout << "-------------------------" << std::endl; std::vector<std::shared_ptr<quote>> sv; for(unsigned i = 0; i != 10; ++i){ sv.push_back(std::make_shared<bulk_quote>("01", 100, 10, 0.1)); } double total1 = 0; for(const auto s : sv){ total1 += s->net_price(20); } std::cout << total1 << std::endl; }
执行结果:
20000 ------------------------- 18000