c++继承中有关shared_ptr的一些疑问
class Basket {
public:
void add_item(const std::shared_ptr<Quote>& q) {
item.insert(q);
}
double print_price(std::ostream& os) const{
double sum=0;
for (auto i = item.cbegin(); i != item.cend(); i = item.upper_bound(*i)) {
sum += print_total(os, **i, item.count(*i));
}
os << "书的总价格为:" << sum << std::endl;
return sum;
}
private:
static bool compare(const std::shared_ptr<Quote> &p, const std::shared_ptr<Quote> &q) {
return p->bookNo < q->bookNo;
}
std::multiset<std::shared_ptr<Quote>,decltype(compare)*> item{compare};//2、这里也不太懂
};
其中,BulkQuote是Quote的派生类,代表有打折的书。
int main() {
Basket basket;
BulkQuote a("a", 10, 5, 0.5);
basket.add_item(make_shared<BulkQuote>(a));//1、这里不懂!
basket.print_price(cout);
1、这里为什么写成“ basket.add_item(make_shared<BulkQuote>(a));”就不行,调用的是静态类型,即Quote,得到的是没打折时的价格?非要写成basket.add_item(make_shared<BulkQuote>(“a”,10,5,0.5));才可以呢?
还有,为什么不可以写成"basket.add_item(new BulkQuote(a));"提示"不存在从'BulkQuote*'到std::shared_ptr<Quote>"的适当构造函数?
2、 item{compare}这里为什么要定义成花括号,之前这里不都是定义成圆括号的吗?还有compare函数需要定义成static的呢?
...全文
相关推荐
求教C++等等一系列的问题
**标准模板库(STL)**:掌握容器(vector、list、map等)、算法(sort、find等)和迭代器的基本用法;了解适配器模式在STL中的应用;掌握智能指针(shared_ptr/unique_ptr
C/C++中文帮助文档.chm
C++的内存管理也是学习的重点,文档会讲解动态内存分配(new和delete操作符)、智能指针(如unique_ptr、shared_ptr、weak_ptr)以及内存泄漏的避免策略。
C++Primer第五版习题答案
**智能指针**:为了解决原始指针可能导致的内存泄漏问题,C++11引入了智能指针,如unique_ptr、shared_ptr和weak_ptr,它们自动管理对象的生命周期。8.
C++参考手册.zip
**智能指针(Smart Pointers)**:C++11引入的智能指针(如unique_ptr、shared_ptr、weak_ptr)可以自动管理内存,防止内存泄漏。8.
【C++ 深入浅出】智能指针shared_ptr、unique_ptr、weak_ptr详解
"深入理解C++中的智能指针,包括shared_ptr、unique_ptr和weak_ptr,以及它们在防止内存泄漏中的作用。"在C++编程中,智能指针是管理动态分配内存的有效工具,它们能自动释


新手乐园
