Область переменных класса C ++ - PullRequest
0 голосов
/ 28 февраля 2012

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

Класс должен иметь открытые функции-члены для покупки напитка и отображения меню, а также закрытые функции для получения и проверки ввода денег (вызываемого buy_drink) и отображения отчета на конец дня (вызываемого деструктором)..

У меня проблема с областью действия в закрытой функции input_money.Я получаю сообщение о том, что массив еще не определен.Я протестировал функцию display_data (для печати меню), и она сама по себе работала нормально, но теперь я не могу понять, почему input_money выдает ошибку области видимости, а display_data - нет.Вот заголовочный файл:

/* need to create a class that holds an array of 
   5 structures, each structure holding string drink name,
   double cost, and int number in machine

   class needs public functions to display data and
   buy drink

   private functions input money -- called by buy_drink to accept,
     validate, and return to buy drink the amount of money input

   daily report -- destructor that reports how much money
     was made daily and how many pops are left in machine */

#ifndef DRINKS_H
#define DRINKS_H
#include <string>

class Drinks
{
 private:
  struct Menu
  {                                   
    std::string name;                 
    double cost;
    int number;
  };
  Menu list[5];             // array of 5 menu structures
  double money_made;        // track money made during the day
  double input_money(int);  // return validated money to buy_drink()
  void daily_report();      // called by deconstructor

 public:
  Drinks();              
  ~Drinks();             
  void display_data();
  void buy_drink(int);
};
#endif

А вот файл реализации:

/* implementation file for Drinks class */

#include <iostream>
#include <string>
#include "drinks.h"
using namespace std;

const int SIZE = 5;
const int START_SIZE = 100;

Drinks::Drinks()
{
  list[0].name = "Coke";
  list[1].name = "Root Beer";
  list[2].name = "Orange Soda";
  list[3].name = "Grape Soda";
  list[4].name = "Bottled Water";

  for (int count = 0; count < (SIZE-1); count++)
    list[count].cost = .75;
  list[4].cost = 1;

  for (int count = 0; count < SIZE; count++)
    list[count].number = 20;

  money_made = 0;
}

void Drinks::display_data()
 {
  for (int count = 0; count < SIZE; count++) {
    if (count == 0)
      cout << count+1 << list[count].name << "\t\t$ ";
    else
      cout << count+1 << list[count].name << "\t$ ";
    cout << list[count].cost << "\t"
     << list[count].number << endl;
  }
}

double input_money(int c)
{
  double input;

  cin >> input;

  while (input != list[c].cost) {
    if (input < list[c].cost) {
      cout << "Not enough money.\n"
       << "Enter " << list[c].cost - input
       << " more cents to buy\n\n> ";
      cin >> input;
    }
    else if (input > list[c].cost) {
      cout << "Too much money.\n"
       << "I only need $" << list[c].cost << endl
       << "Enter " << input - list[c].cost
       << " less money: ";
      cin >> input;
    }
  }

  return input;
}

void Drinks::buy_drink(int c)                // this receives an int choice (to access corresponding structure in the list array)
{ 
  double input;                              
  cout << "Enter " <<list[c].cost             
       << " to purchase " << list[c].name    
       << "\n\n> ";                           
  input = input_money(c);                    // input money returns a validated and accurate price for the drink and is passed the choice to access array

  list[c].number -= 1;
  money_made += list[c].cost;                // add cost of drink to money made
}

void Drinks::daily_report()
{
  int end_size = 0;

  for (int count = 0; count < SIZE; count++)
    end_size += list[count].number;

  cout << "Today, you made $" << money_made << endl;
  cout << "There are " << START_SIZE - end_size
       << " drinks left in the machine" << endl;
}

Drinks::~Drinks()
{
  daily_report();

  cout << "goodbye mr anderson\n";
}

Любая помощь будет высоко ценится!Кажется, я не могу понять, почему функция input_money не имеет доступа к структурам в массиве.

Спасибо!

РЕДАКТИРОВАТЬ: Общая ошибка нуба / небрежность.Забыл добавить имя класса в определении функции input_money и использовать оператор разрешения области видимости (т.е. должен быть Drinks :: input_money (int c)).Спасибо тем, кто ответил.

Ответы [ 2 ]

5 голосов
/ 28 февраля 2012
double Drinks::input_money(int c) 
    // ^^^^^^^^ forgot this

Вы забыли имя класса, предоставляя реализацию.

1 голос
/ 28 февраля 2012

Обратите внимание на разницу между вашим определением

void Drinks::display_data

и

double input_money(int c)

Во втором случае вы определили свободную функцию, которая не является членом класса и не имеет информации о членах класса. Должно быть

double Drinks::input_money(int c)

...