NibA_NibA Ответов: 3

Я работаю над своей программой под названием "система заказа еды". Это дает мне некоторые ошибки, как я их исправляю?


#include<iostream>
#include<conio.h>
using namespace std;

class pizza
{
	public:
		int choice=0;
		int pchoice,pchoice1, quantity;
		char pizza1='Chicken Fajita' ,pizza2='Chicken Bar BQ' ,pizza3='Chicken Tikka' ,pizza4='Chicken Cheese'; 
		int getdata()
		{
			cout<<"1) "<<pizza1<<endl;
			cout<<"2) "<<pizza2<<endl;
			cout<<"3) "<<pizza3<<endl;
			cout<<"4) "<<pizza4<<endl<<endl;
			cout<<"Please Enter which Flavour would you like to have? : ";
			cin>>pchoice;
			cout<<endl;
		if(pchoice>=1 && pchoice<=5)
		{
			cout<<"1) Small Rs.250"<<endl;
			cout<<"2) Regular Rs.500"<<endl;
			cout<<"3) Large Rs.900"<<endl<<endl;
			cout<<"Choose Size of Pizza Please : ";
			cin>>pchoice1;
			if(pchoice1>=1 && pchoice1<=3)
			cout<<endl;
			cout<<"Please Enter Quantity: ";
			cin>>quantity;
			switch(pchoice1)
			{
			case 1: choice = 250*quantity;
			break;
			case 2: choice = 500*quantity;
			break;
			case 3: choice = 900*quantity;
			break;
			}
			system("CLS");
			switch (pchoice1)
			{
			 case 1:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<pizza1<<endl;
			 cout<<"Your Total Bill is"<<choice<<endl<<"Your Order Will be delivered in 30 Minutes";
			 cout<<endl<<endl;
			 cout<<"------Thank you For Ordering From Niba and Rohma Fast Food------"<<endl;
			 break;
			 case 2:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<"  "<<pizza2<<endl;;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 30 Minutes";
			 cout<<endl<<endl;
			 cout<<"------Thank you For Ordering From Niba and Rohma Fast Food------"<<endl;
			 break;
			 case 3:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<pizza3<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 30 Minutes";
			 cout<<endl<<endl;
			 cout<<"------Thank you For Ordering From Niba and Rohma Fast Food------"<<endl;
			 break;
			 case 4:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<pizza4<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 30 Minutes";
			 cout<<endl<<endl;
			 cout<<"------Thank you For Ordering From Niba and Rohma Fast Food------"<<endl;
			 break;

			}
			cout<<"Would you like to order anything else? Y / N:";
			cin>>gotostart;
			if(gotostart=='Y' || gotostart=='y')
			{
			  goto beginning;
			  //return 0;
			}
		}
		}
};
class burger
{
	public:
		int choice=0;
		int pchoice,pchoice1, quantity;
		char bur1='Zinger Burger',bur2='Chicken Burger',bur3='Beef Burger';
	int getdata()
	{
		cout<<"1) "<<bur1<<" Rs.100"<<endl;
		cout<<"2) "<<bur2<<" Rs.150"<<endl;
		cout<<"3) "<<bur3<<" Rs.200"<<endl;
		cout<<"Please Enter which Burger you would like to have?: ";
		cin>>pchoice1;
		if(pchoice1>=1 && pchoice1<=3)
		{
			cout<<endl;
			cout<<"Please Enter Quantity: ";
			cin>>quantity;
			switch(pchoice1)
			{
			case 1: choice = 100*quantity;
			break;
			case 2: choice = 150*quantity;
			break;
			case 3: choice = 200*quantity;
			break;
			}
			system("CLS");
			switch (pchoice1)
			{
			 case 1:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<bur1<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 40 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 case 2:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<bur2<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 40 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 case 3:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<bur3<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 40 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 break;
			}
			cout<<endl;
			cout<<"Would you like to order anything else? Y / N:";
			cin>>gotostart;
			if(gotostart=='Y' || gotostart=='y')
			{
			  goto beginning;
			  //return 0;
			}
 		}
	}
};
class sandwich
{
	public:	
	int choice=0;
	int pchoice,pchoice1, quantity;
	char sand1='Club Sandwich', sand2='Chicken Crispy Sandwich', sand3='Extream Veg Sandwich';
	int getdata()
	{
		cout<<endl;
		cout<<"1)  "<<sand1<<" Rs.240"<<endl;
		cout<<"2)  "<<sand2<<" Rs.160"<<endl;
		cout<<"3)  "<<sand3<<" Rs.100"<<endl<<endl;
		cout<<"Please Enter which Sandwich you would like to have? : ";
		cin>>pchoice1;
		if(pchoice1>=1 && pchoice1<=3)
		{
			cout<<endl;
			cout<<"Please Enter Quantity: ";
			cin>>quantity;
			switch(pchoice1)
			{
			case 1: choice = 240*quantity;
			break;
			case 2: choice = 160*quantity;
			break;
			case 3: choice = 100*quantity;
			break;
			}
			system("CLS");
			switch (pchoice1)
			{
			 case 1:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<sand1<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 50 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 break;
			case 2:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<sand2<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 50 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 break;
 			case 3:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<sand3<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 50 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 break;
			}
			cout<<"Would you like to order anything else? Y / N:";
			cin>>gotostart;
			if(gotostart=='Y' || gotostart=='y')
			{
			  goto beginning;
			  //return 0;
			}
		}
	}
};
class roll
{
	public:
		int choice=0;
		int pchoice,pchoice1, quantity;
		char roll1='Chicken Chatni Roll', roll2='Chicken Mayo Roll', roll3='Veg Roll With Fries';
		int getdata()
		{
		cout<<"1) "<<roll1<<" Rs.150"<<endl;
		cout<<"2) "<<roll2<<" Rs.100"<<endl;
		cout<<"3) "<<roll3<<" Rs.120"<<endl<<endl;
		cout<<"Please Enter which you would like to have?: ";
		cin>>pchoice1;
		if(pchoice1>=1 && pchoice1<=3)
		{
			cout<<endl;
			cout<<"How Much Rolls Do you want: ";
			cin>>quantity;
			switch(pchoice1)
			{
			case 1: choice = 150*quantity;
			break;
			case 2: choice = 100*quantity;
			break;
			case 3: choice = 120*quantity;
			break;
			}
			system("CLS");
			switch (pchoice1)
			{
			 case 1:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<roll1<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 60 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 break;
			case 2:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<roll2<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 60 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 break;
			case 3:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<roll3<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 60 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food"<<endl;
			 break;
			}
 		}
	}
		
};
class biryani
{
	public:
		int choice=0;
		int pchoice,pchoice1, quantity;
		char bir1='Chicken Biryani', bir2='Sindhi Biryani', bir3='Beef Biryani';
		int getdata()
		{
			cout<<"1) "<<bir1<<" Rs.160"<<endl;
		cout<<"2) "<<bir2<<" Rs.220"<<endl;
		cout<<"3) "<<bir3<<" Rs.140"<<endl<<endl;
		cout<<"Please Enter which Biryani you would like to have?:";
		cin>>pchoice1;
		if(pchoice1>=1 && pchoice1<=3)
		{
			cout<<endl;
			cout<<"Please Enter Quantity: ";
			cin>>quantity;
			switch(pchoice1)
			{
			case 1: choice = 160*quantity;
			break;
			case 2: choice = 220*quantity;
			break;
			case 3: choice = 140*quantity;
			break;
			}
			system("CLS");
			switch (pchoice1)
			{
			 case 1:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<bir1<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 30 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food "<<endl;
			 break;
			 case 2:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<bir2<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 30 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food "<<endl;
			 break;
			 case 3:
			 cout<<"\t\t--------Your Order---------"<<endl;
			 cout<<""<<quantity<<" "<<bir3<<endl;
			 cout<<"Your Total Bill is "<<choice<<endl<<"Your Order Will be delivered in 30 Minutes"<<endl;
			 cout<<"Thank you For Ordering From NibA and Rohma Fast Food "<<endl;
			 break;
			}
			cout<<"Would you like to order anything else? Y / N:";
			cin>>gotostart;
			if(gotostart=='Y' || gotostart=='y')
			{
			  goto beginning;
			  //return 0;
			}
		}
	}
};
class food
{
	private:
			char name[30];

			int choice=0;
			int pchoice,pchoice1, quantity;
			pizza p;
			burger b;
			sandwich s;
			roll r;
			biryani bi;
		public:
		int getdata()
		{
			beginning:
			system("CLS");
			cout<<"\t\t----------NibA and Rohma Fast Food-----------"<<endl<<endl;
			cout<<"Please Enter Your Name: ";
			cin>>name;
			cout<<"Hello "<<name<<endl<<"What would you like to order?"<<endl<<endl;
			cout<<"\t--------Menu--------"<<endl<<endl;
			cout<<"1) Pizzas"<<endl;
			cout<<"2) Burgers"<<endl;
			cout<<"3) Sandwich"<<endl;
			cout<<"4) Rolls"<<endl;
			cout<<"5) Biryani"<<endl;
			cout<<endl;
			cout<<"Please Enter your Choice: ";
			cin>>choice;
			if(choice==1)
			{
				p.getdata();
			}
			else if(choice==2)
	 		{
				b.getdata();
			}
			else if(choice==3)
			{
				s.getdata();
			}
			else if(choice==4)
			{
				r.getdata();
			}
			else if(choice==5)
			{
				bi.getdata();
			}
			else
			{
				system("CLS");
				cout<<"Please Select Right Option: "<<endl;
				cout<<"Would You like to Start the program again? Y / N: " ;
				cin>>gotostart;
				if(gotostart=='Y' || gotostart=='y')
				{
				  goto beginning;
			  //return 0;
				}
			}
		}
};

int main()
{
	food f;
	f.getdata();
	getch();		
}


Что я уже пробовал:

код выдает мне эти ошибки:
1. [предупреждение] переполнение при неявном преобразовании констант [-Woverflow]
2. [Ошибка] 'gotostart' не был объявлен в этой области
3. [ошибка] метка "начало" используется, но не определена>
4. [предупреждение] нестатические инициализаторы элементов данных доступны только с-std=c++11 или -std=gnu++11

3 Ответов

Рейтинг:
21

Rick York

I believe Mr. K5054 has given very valuable advice. After looking over your code, I think you should step back and take a "bigger picture" look at your code. I noticed you have a common pattern in your classes that should be moved into a base class that other classes derive from. This base class will do the following : display a list of the options and their prices; accept input of the choice(s) and quantities; display order summary, cost, and estimate of delivery time. Every single one of your food classes does these same things. The only differences are their text names, prices, and delivery times so each of these should be data parameters. I would make two classes to handle this. One would be a food item that contains a text name (used in prompting) and a cost. The second would be the order. It contains groups of food items, the total cost, and an estimated delivery time for them. This class would be the base class mentioned above.

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

class FoodItem
{
public:
   const char * name  { nullptr };
   int cost           { 0 };
   int count          { 0 };

public:
   FoodItem()  {}

   FoodItem( const char * n, int c ) { Set( n, c ); }

   void Set( const char * n, int c )
   {
       name = n;
       cost = c;
   }

   int GetCost() const
   {
       return count * cost;
   }
};

// here are some instances

const FoodItem biryanis[3];
biryani[0].Set( "Chicken Biryani", 160 );
biryani[1].Set( "Sindhi Biryani", 220 );
biryani[2].Set( "Beef Biryani", 140 );
Вы можете определить группы продуктов питания для каждого типа, который у вас есть. Затем реализуйте класс, который выполняет запрос и получает данные заказа. Вот прототип функции, которая получает заказ :
int GetOrder( FoodItem items[], int itemcount, int deliveryTime );

//and you could call it like this:

int rv = GetOrder( biryanis, 3, 30 );
Обратите внимание, что класс продуктов питания содержит количество заказанных продуктов. Вы можете сделать несколько групп продуктов питания, по одной для каждого вида, и это будет представлять один заказ. Вот то, что данные-члены для класса того, как может выглядеть:
class FoodOrder
{
public:
   FoodItem pizzas[3];
   FoodItem burgers[3];
   FoodItem sandwiches[3];
   FoodItem rolls[3];
   FoodItem biryanis[3];
};
If this were my project, I would split the name into two parts : a type (biryani) and the variety (chicken). Then I would have a vector for all of those so I could have as many of them as I wanted to. The prompting would first ask for what type and then it would display a list of all options of that type. It would make things much more flexible and open-ended. In fact, you could have a vector of food types and options with no limit on either. If you wanted, you could view this as configuration data that is loaded from a file when the program starts. The program could figure out how many different types there are and operate accordingly.


Рейтинг:
13

k5054

1. Не многие люди собираются пробираться через 300+ строк кода, чтобы выяснить, что переполнено. Пожалуйста, укажите номера строк для предупреждений/ошибок, которые вы получаете.

2. Вы забыли дать определение gotostart Взгляните на свою программу и решите, где лучше всего ее определить.

3. у вас есть goto но никакой ярлык не определен. Добавьте метку. В целом, однако, использование goto этого следует избегать. Если это школьное задание, вы, вероятно, получите баллы, вычитаемые за использование goto.

4. только статические члены класса могут быть инициализированы во время компиляции. Если вы хотите инициализировать переменные при построении объекта класса, вы должны использовать класс constructor метод, что-то вроде

class MyClass {
int counter;
public:
    MyClass() {
       counter = 0;
    }
}


Есть и другие вещи, которые я тоже замечаю, например, вы должны получать ошибку на
char pizza1='Chicken Fajita', ...
Переменные типа char это один символ. Вероятно, вам нужен массив символов, например
char pizza1[] = "Chicken Fajita"
, или еще лучше c++ string тип. Но даже в этом случае это не способ создания элемента класса с постоянным строковым именем .. см. (4) выше.

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


Рейтинг:
1

KarstenK

Не используйте goto, но цикл while с каким-то флагом. Присмотритесь внимательнее к строчкам, о которых жаловался ваш компилятор.

bool looping = true;

while( looping ) {

 // some exit case 
looping = false;
}
Это не должно быть слишком сложно.