2010-05-25 5 views
0

Моя задача следующая:Указатели на поля классов

С помощью указателей на поля классов создайте меню, позволяющее выбирать лед, который человек может купить в магазине льда. Покупателю будут взиматься расходы на вафли и лед.

Подбор льда и поручения покупателей должен быть показан в программе.

Вот мой класс Person:

#include <iostream> 
using namespace std; 

class Iceshop { 
    const double waffel_price = 1; 
public: 

} 
class Person { 
    static int NUMBER; 
    char* name; 
    int age; 
    const int number; 
    double plus, minus; 
public: 

    class Account { 
     int number; 
     double resources; 

     public:  
      Account(int number, double resources) 
       : number(number), resources(resources) 
      {}  
    } 

    Person(const char* n, int age) 
     : name(strcpy(new char[strlen(n)+1],n)), 
      number(++NUMBER), plus(0), minus(0), age(age) 
    {} 


    Person::~Person(){ 
     cout << "Destroying resources" << endl; 
     delete [] name; 
    } 

    friend void show(Person &p); 

    int* take_age(){ 
     return &age; 
    } 

    char* take_name(){ 
     return name;  
    } 

    void init(char* n, int a) { 
     name = n; 
     age = a; 
    } 

    Person& remittance(double d) { plus += d; return *this; } 
    Person& paycheck(double d) { minus += d; return *this; } 
    Account* getAccount(); 

}; 

int Person:: 

Person::Account* Person::getAccount() { 
    return new Account(number, plus - minus); 
} 


void Person::Account::remittance(double d){ 
    resources = resources + d; 
} 

void Person::Account::paycheck(double d){ 
    resources = resources - d;  
} 

void show(Person *p){ 
    cout << "Name: " << p->take_name() << "," << "age: " << p->take_age() << endl; 
} 

int main(void) { 
    Person *p = new Person; 
    p->init("Mary", 25); 

    show(p); 

    p->remittance(100); 

    system("PAUSE"); 
    return 0; 
} 

Как изменить это в использовании указателей на поля?

class Iceshop { 
    const double waffel_price; 
    int menu_options; 
    double[] menu_prices; 
    char* menu_names; 
    char* name; 
public: 

    IceShop(char*c) 
     : name(strcpy(new char[strlen(n)+1],n)), 
       waffel_price(1), menu(0) 
    {} 

    void init(int[] n){ 
     menu_options = n; 
    } 

    void showMenu(Iceshop &i){ 
     int list; 
     list = &i 
     char* sorts = i->menu_names; 
     int count=0; 

     while(count < list){ 
       cout << count+1 << ")" << sorts[count] << endl; 
       ++count; 
     }   
    } 

    void createMenu(Iceshop *i){ 
     for(int j=0; j <(i->menu_options), ++j){ 
       cout << "Ice name: "; 
       cin >> i->menu_names[j]; 
       endl; 
       cout << "Ice cost: " 
       cin >> i->menu_prices[j]; 
       endl; 
     } 
    } 

    void chargeClient(Person *p, Iceshop* i, int sel){ 
     p->remittance((i->menu_prices[sel])+(i->waffel_price));   
    } 

}; 
+0

Приятный новый ник) –

+0

Кроме того, ваш 'showMenu' чрезвычайно злой. Я бы порекомендовал вам сказать себе, что вы хотите сделать, прежде чем прикасаться к клавиатуре. То, что вы делаете сейчас, можно охарактеризовать как «Передавать другому объекту Iceshop этому объекту, принимать его адрес и выполнять итерацию, в то время как счетчик меньше этого адреса (SIC!)' –

ответ

0

Вы можете попытаться создать интерфейс, управляемый меню. Что-то вроде этого (копия пасты с форума, для большего количества примеров поиска меню «C++ консоли»»или что-то вроде этого на Google.

int choice = 0; 

while (choice != 4) 
{ 
cout <<"Enter choice:"<< endl << 
"1) ice 1" << endl << 
"2) ice 2" << endl<< 
"3) ice 3" << endl << 
"4) exit" << endl; 

cin >> choice; 

switch(choice) 
{ 
    case 1: 
    //show menu to buy or cancel 
    break; 
    case 2: 
    //show menu to buy or cancel 
    break; 
} 
//etc 
} 
0

Вот что я хотел бы сделать. Обратите внимание, что это не совсем то, что вам «Ищем и, ну, абстрактное моделирование ситуации всегда жесткое :)

Но я надеюсь, что этот код заставит вас понять, что вы должны делать.

Кроме того, я не совсем уверен в использовании указателей для полей классов, потому что это имеет тенденцию быть ситуацией, когда использование указателя является сверхплотным.

#include <vector> 
#include <string> 
#include <algorithm> 
#include <iostream> 

// Some abstract type used to measure prices 
typedef size_t money_t; 

struct Item { 
    // Item's name and price 
    std::string name; 
    money_t price; 

    // Could also have something that makes 
    // it an item, but this is not necessary 

    // This could be anything, because we're actually 
    // modelling an abstract situation 

    // (...) 

    // Note that we don't allow unnamed items 
    Item(const std::string& name, const money_t& price = 0) : name(name), price(price) { } 

    // Note here that items are treated as 'same' only by names 
    // This means we're actually talking about 'logical groups' of items 
    bool operator==(const Item& item) const { return name == item.name; } 
    bool operator==(const std::string& item_name) const { return name == item_name; } 
}; 

class Store { 
private: 
    // Store's item storage 

    // Note that items actually represent infinite groups 
    // of items (in our case store is an abstract store 
    // which items simply can't end) 
    std::vector<Item> items; 

public: 
    // Initialize a store that doesn't sell anything 
    Store() { } 

    // Initialize a store that could sell specified types of items 
    Store(const std::vector<Item>& items) : items(items) { } 

    // Show what we actually sell in this store 
    void EnumerateItems() const { 
     for (size_t i = 0; i < items.size(); ++i) 
     std::cout << items[i].name << " : " << items[i].price << "\n"; 
    } 

    Item Sell(const std::string& name) const { 
     // Find appropriate item in the item list 
     std::vector<Item>::const_iterator what = std::find(items.begin(), items.end(), name); 

     // If nothing found, throw an exception 
     if (what == items.end()) { 
     throw std::domain_error("Store doesn't sell this type of item"); 
     } 
     // Return item as a sold one 
     return (*what); 
    } 
}; 

class Person { 
private: 
    // Person's name (identity) 
    std::string name; 

    // Item's that are currently possesed 
    // by this person 
    std::vector<Item> owned_items; 

    // Amount of cash that this person has 
    money_t cash; 

public: 
    // Note that we don't allow unnamed persons 
    Person(const std::string& name, const money_t& cash = 0) : name(name), cash(cash) { } 

    void Buy(const Item& what) { 
     owned_items.push_back(what); 
     cash -= what.price; 
    } 
}; 

void GoShopping(Person& person, const Store& store) { 
    // Let's simulate buying one item 

    // You could easily make a loop and determine what to buy in 
    // every loop iteration 

    store.EnumerateItems(); 
    person.Buy(store.Sell("Shoes")); 
} 

int main() { 
    // Initialize our store that sells only shoes 
    std::vector<Item> items; 
    items.push_back(Item("Shoes", 25)); 

    Store grocery(items); 
    // Initialize our person 
    Person jim_carrey("Jim Carrey", 500); 

    // The yummy part 
    GoShopping(jim_carrey, grocery); 

    return 0; 
} 
Смежные вопросы