Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

15.8.1 调用net_price虚函数 #48

Open
werkgg opened this issue Oct 7, 2015 · 4 comments
Open

15.8.1 调用net_price虚函数 #48

werkgg opened this issue Oct 7, 2015 · 4 comments

Comments

@werkgg
Copy link

werkgg commented Oct 7, 2015

double Basket::total_receipt(ostream &os) const
{
    double sum = 0.0; // holds the running total
    // iter refers to the first element in a batch of elements with the same ISBN
    // upper_bound returns an iterator to the element just past the end of that batch
    for (auto iter = items.cbegin();
            iter != items.cend();
            iter = items.upper_bound(*iter)) {
        // we know there's at least one element with this key in the Basket
        // print the line item for this book
        sum += print_total(os, **iter, items.count(*iter));
    }
    os << "Total Sale: " << sum << endl; // print the final overall total
    return sum;
}

这里print_total会调用net_price虚函数. 按照书上的解释, 最终的price的计算结果取决于**item的dynamic type. 可是当我们调用add_item的时候, 相同的isbn(), 我们可能加入Quote type也可能会加入bulk_Quote type.

item是相同isbn()的batch的第一个元素. 那么我们怎么来判断item的dynamic type呢?

比如调用add_item的时候, 第一个加入的是Quote, 第二个是bulk_Quote, 第三个是Quote, 第四个是bulk_Quote...

@pezy
Copy link
Member

pezy commented Oct 8, 2015

那么我们怎么来判断item的dynamic type呢?

没看出来哪里需要判断啊? 根据各自类型, 调用各自的 net_price 实现. 这不就是多态要干的事情吗?

@werkgg
Copy link
Author

werkgg commented Oct 8, 2015

比如同一个ISBN,我们先加入Quote类型,再加入bulk_quote类型。**iter应该是Quote类型吧?bulk_quote怎么处理?

@pezy
Copy link
Member

pezy commented Oct 8, 2015

**iter应该是Quote类型吧?bulk_quote怎么处理?

应该是: static type 是 Quote, dynamic type 可不一定, 要看你放入的是什么. (Quote 的就是 Quote, bulk_quote 的就是 bulk_quote) .

建议温习一下 15.2.3 的 Static Type and Dynamic Type 一节.

@werkgg
Copy link
Author

werkgg commented Oct 8, 2015

如果加入的是同一ISBN,按照total_receipt中定义,_iter每次都指向相同ISBN的第一个元素(不论是Quote或者bulk_quote):
for (auto iter = items.cbegin();
iter != items.cend();
iter = items.upper_bound(_iter)) {
// we know there's at least one element with this key in the Basket
// print the line item for this book
sum += print_total(os, *_iter, items.count(_iter));
}

print_total中,**iter的dynamic type是同样ISBN中的第一个元素的类型.

所以如果我们先加入Quote,再加入bulk_quote,则**iter的dynamic type是Quote.net_price相应的dynamic type也是Quote.

如果先加入bulk_quote,再加入Quote,则**iter的dynamic type就变成bulk_quote.net_price相应的dynamic type也是bulk_quote.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants