C++在容器中放置有继承关系的对象和指针区别
《C++ Primer 5》15.28和15.29两题
1 .h头文件:包括父类Quote和子类Bulk_quote的定义
bookQuote.h:
#pragma once
#include<iostream>
#include<string>
using namespace std;
class Quote {
//friend ostream& operator<<(ostream&, Quote&);
public:
Quote() = default;
Quote(const string& book = "", double sales_price = 0.0) :bookNo(book), price(sales_price) {}
string isbn() const {
return bookNo;
}
virtual double net_price(size_t n) const {
return n * price;
}
virtual ~Quote(){}
private:
string bookNo;
protected:
double price = 0.0;
};
class Bulk_quote :public Quote {
public:
Bulk_quote(const string& book = "", double sales_price = 0.0, size_t qty = 0, double disc = 0.0) :
Quote(book, sales_price), min_qty(qty), discount(disc) {}
double net_price(size_t cnt) const {
if (cnt > min_qty) {
return cnt * (1 - discount) * price;
}
else {
return cnt * price;
}
}
~Bulk_quote(){}
private:
size_t min_qty;
double discount;
};
2-1 .cpp文件:定义父类Quote对象的vector容器,存入子类Bulk_quote对象
#include<iostream>
#include<string>
#include<vector>
#include"bookQuote.h" //1中定义的.h头文件
#include<memory> //shared_ptr智能指针
using namespace std;
int main() {
vector<Quote> itemVec;
for (size_t i = 0;i != 10;++i) {
Bulk_quote item("C++ Primer 5", 6, 5, 0.5);
itemVec.push_back(item);
}
double sum = 0;
for (auto iter = itemVec.begin();iter != itemVec.end();++iter) {
sum += iter->net_price(10);
}
cout << sum << endl;
return 0;
}
输出结果,600。
2-2 .cpp文件:定义指向父类Quote对象的智能指针的vector容器,存入指向子类Bulk_quote对象的智能指针
#include<iostream>
#include<string>
#include<vector>
#include"bookQuote.h"
#include<memory>
using namespace std;
int main() {
vector<shared_ptr<Quote>> itemVec;
for (size_t i = 0;i != 10;++i) {
Bulk_quote item("C++ Primer 5", 6, 5, 0.5);
itemVec.push_back(make_shared<Bulk_quote>(item));
}
double sum = 0;
for (auto iter = itemVec.begin();iter != itemVec.end();++iter) {
sum += (*iter)->net_price(10);
}
cout << sum << endl;
return 0;
}
输出结果:300。