問題:類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