Указатели на поля класса - PullRequest
0 голосов
/ 25 мая 2010

Моя задача заключается в следующем:

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

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

Вот мой класс 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) );        
    }

};

Ответы [ 2 ]

0 голосов
/ 25 мая 2010

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

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

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

#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;
}
0 голосов
/ 25 мая 2010

Вы можете попытаться создать управляемый меню пользовательский интерфейс. Примерно так (скопируйте вставку с форума, для других примеров найдите «меню консоли 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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...