#include<iostream>
#include<vector>
using namespace std;
class Book;
class Visitor
{
public:
virtual void visit(Book* book) = 0;
//其他物品的visit方法
};
class Item
{
public:
virtual void accept(Visitor* visitor) = 0;
virtual double getPrice() = 0;
};
class Book : public Item //(1)
{
private:
double price;
public:
Book(double price)
{
//访问本元素
this->price = price; //(2)
}
void accept(Visitor* visitor)
{
visitor->visit(this); //(3)
}
double getPrice()
{
return price;
}
};
class Cashier : public Visitor //(4)
{
private:
double totalForCart;
public:
//访问BooK类型对象的价格并累加
void visit(Book* book) //(5)
{
if(book->getPrice()<10.0) //假设Book类型的物品价格超过10元打8折
{
totalForCart += book->getPrice();
}
else
{
totalForCart += book->getPrice() * 0.8;
}
}
double getTotal()
{
return totalForCart;
}
};
class ShoppingCart
{
private:
vector<Item*> items;
public:
double calculatePrice()
{
Cashier* visitor = new Cashier();
for(int i=0;i<items.size();i++)
{
items.at(i)->accept(visitor); //(6)
}
double total = visitor->getTotal();
return total;
}
void add(Item* e)
{
items.push_back(e);
}
};
int main()
{
return 0;
}
答案:
(1) : public Item
(2) this->price = price
(3) visitor->visit(this); //易错
(4) : public Visitor
(5) void visit(Book* book)
(6) items.at(i)->accept(visitor);