Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 06.06.2009, 01:43   #1
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию Задача на наследование...не могу отловить ошибку

Вот собственно сам код. Необходимо по задаче сложить составляющие блюда. Все ингридиенты в файле в форме:
meat sirloin beef 200
fruit apple sweet 132
vegetable carrot home 42
Заранее спасибо тому, кто отловит.
main.cpp
Код:
#include <iostream>
#include <fstream>
#include "Product.h"
using namespace std;
int main()
{
	Meat meat1;
	Fruit fruit1;
	Vegetable veg1;
	int t=0;
	char buf[100];	
	char*s1 = new char[20];
	char*s2 = new char[20];
	char*s3 = new char[20];
	char*s4 = new char[20];
	ifstream stream ("Ingridient.txt");    
	if (!stream) 
	{
		error ("Ingridient.txt");
	}
	while(!stream.eof())
	{
		stream.getline(buf,100,'\n');
		t++;
	}
	stream.close();
	ifstream stream2 ("Ingridient.txt");
	if (!stream2) 
	{
		error ("Ingridient.txt");
	}
	Product * prod = new Product [t];
	Dish dish(t);
	int i = 0;
	while (!stream2.eof())
	{ 
		stream2 >> s1 >> s2 >> s3 >> s4;
		if(s1[0] == 'm')
		{
			Meat meat (s2,s3,s4); 
			meat1 = meat;
			prod[i] = meat1;
			i++; 
		}
		if(s1[0] == 'f')
		{
			cout<<"dfd";
			Fruit fruit (s2,s3,s4); 
			fruit1 = fruit;
			prod[i] = fruit1;;
			i++;
		}
		if(s1[0] == 'v')
		{
			Vegetable veg (s2,s3,s4); 
			veg1 = veg;
			prod[i] = veg1;
			i++;
		}
	}
	for(int j=0;j<t;j++)
	{
		dish += prod[j];
	}
	cout << "Result: \n" << dish;
	stream2.close();
	delete [] s1;
	delete [] s2;
	delete [] s3;
	delete [] s4;
	system ("PAUSE");
	return 0;
}
String.h
Код:
#ifndef String_h
#define String_h
#include <iostream>
using namespace std;

class String 
{ 
private:
		int size;
		char *str;
public:
		String ();
		~String();
		String (const String & st);
		String & operator =(const String &st);
		String operator + (const String & st);
		String & operator =(const char *st);
		String & operator += (const String & st);
		friend ostream &operator<<(ostream&, String &st);
};

#endif
<= P.S. если я тебе помог нажми весы слева <=
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 01:43   #2
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию

Product.h
Код:
#ifndef Product_h
#define Product_h
#include <iostream>
#include "String.h"
using namespace std;
void error ( const char * file_name )
{             
cout << "\nCan't open " << file_name << '\n';
exit(1);
}
class Product
{
protected:
    String name;
	int foodValue;
public:
	~Product();
	Product ();
	String & Isname ();
	int IsFoodValue();
	Product (const char * s2, const char * s4);
	virtual String & Word ();
};
Product ::~Product()
{
}
String & Product ::Word ()
{
	return name;
}
Product :: Product ()
{}
String & Product ::Isname ()
{
	return name;
}
int Product::IsFoodValue ()
{
	return foodValue;
}
Product::Product (const char * s2, const char * s4)
{
	name = s2; 
	this->foodValue = atoi(s4);
}
class Meat: public Product
{
private:
	String Type;
public:
	Meat ();
	Meat(const char * s2, const char * s3, const char * s4);
	Meat & operator = (const Meat & st);
	~Meat();
	String & Word ();
};
Meat & Meat::operator = (const Meat & st)
{
	this->foodValue = st.foodValue;
	this->name = st.name;
	this->Type = st.Type;
	return (*this);
}
Meat::Meat ():Product()
{}
String & Meat::Word()
{
	return Type;
}
Meat::~Meat()
{}
Meat::Meat(const char * s2, const char * s3, const char * s4):Product(s2,s4)
{
	this->Type = s3;
}
class Fruit: public Product
{
private:
	String Sweetness;
public:
	Fruit(const char * s2, const char * s3, const char * s4);
	Fruit & operator = (const Fruit & st);
	~Fruit();
	Fruit ();
	String & Word ();
};
Fruit & Fruit ::operator = (const Fruit & st)
{
	this->foodValue = st.foodValue;
	this->name = st.name;
	this->Sweetness = st.Sweetness;
	return (*this);
}
Fruit ::Fruit():Product()
{}
String & Fruit :: Word()
{
	return Sweetness;
}
Fruit::~Fruit()
{}
Fruit::Fruit(const char * s2, const char * s3, const char * s4):Product(s2,s4)
{
      this->Sweetness = s3;
}
class Vegetable: virtual public Product
{
private:
	String GrowingType;
public:
	Vegetable(const char * s2, const char * s3, const char * s4);
	Vegetable & operator = (const Vegetable & st);
	~Vegetable();
	Vegetable ();
	String & Word ();
};
Vegetable & Vegetable::operator = (const Vegetable & st)
{
	this->foodValue = st.foodValue;
	this->name = st.name;
	this->GrowingType = st.GrowingType;
	return (*this);
}
String & Vegetable::Word()
{
	return GrowingType;
}
Vegetable::Vegetable():Product()
{}
Vegetable::~Vegetable()
{}
Vegetable::Vegetable(const char * s2, const char * s3, const char * s4):Product(s2,s4)
{
	this->GrowingType = s3;
}
class Dish
{
private:
	String * name;
	double dfoodValue;
	int msize;
	static int p;
public:
	Dish(int a);
	friend ostream & operator <<(ostream & stream, Dish & dish);
	Dish & operator += (Product& prod);
};
int Dish::p = 0;
Dish & Dish:: operator += (Product & prod)
{
	dfoodValue += prod.IsFoodValue();
	name[p] = prod.Isname() + prod.Word();
	return (*this);
	p++;
}

ostream & operator << (ostream & stream, Dish & dish)
{
	for(int i=0;i<dish.msize;i++)
	{
		stream << dish.name[i];
	}
	return stream;
}
Dish::Dish(int a)
{
	name = new String [a];
	msize = a;
}
#endif
String.cpp
Код:
#include "String.h"
#include <iostream>
using namespace std;

String::~String()
{
	delete [] str;
}
String ::String()
{
	str = new char [0];
}
String::String (const String & st)
{
	size = st.size;
	str = new char [size];
	strcpy(str,st.str);
}
String String:: operator + (const String & st)
{
	String tmp = *this;
	tmp += st;
	return(tmp);
}
String& String::operator += (const String &st)
{
	char *tmp = new char [size];
	strcpy(tmp, str);
	if(str)
	{
		delete [] str;
	}
	size = st.size + size + 1;
	str = new char [size];
	strcpy(str, tmp);
	strcat(str, st.str);
	delete [] tmp;
	return(*this);
}
String & String::operator=(const String &st)
{
	this->size=st.size;
    if(str)
	{
		delete [] str;
	}
	strcpy(str,st.str);
	return (*this);
}
String & String::operator = (const char *st)
{
	this->size=strlen(st)+1;
    if(str)
	{
		delete [] str;
	}
	strcpy(str,st);
	return (*this);
}
ostream &operator<<(ostream& A, String &st)
{
	A<<st.str;
	return A;
}
<= P.S. если я тебе помог нажми весы слева <=
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 02:08   #3
Sazary
В тени
Старожил
 
Аватар для Sazary
 
Регистрация: 19.12.2008
Сообщений: 5,788
По умолчанию

Вот что заметил:
Ошибка сегментации возникает после после конвертации в конструкторе Product:
Код:
Product::Product (const char * s2, const char * s4)
{
	name = s2;
	this->foodValue = atoi(s4);
}
который вызывается из конструктора Meat:
Код:
Meat::Meat(const char * s2, const char * s3, const char * s4):Product(s2,s4)
который, в свою очередь, вызывается отсюда:
Код:
if(s1[0] == 'm')
		{
			Meat meat (s2,s3,s4);
			meat1 = meat;
			prod[i] = meat1;
			i++;
		}
Притом, если поставить брейкпоинт на место сразу за конвертацией, то видно, что она проходит и число записывается. Но сразу после этого и возникает ошибка..
Вполне очевидно, чтобы что-то понять, необходимо книги читать.
Не нужно плодить бессмысленных тем. Вас Поиск избавит от многих проблем.

___________________________________ ___________________________________ _______
[=Правила форума=]_____[Поиск]_____[Литература по С++]____[Литература. Паскаль]
Sazary вне форума Ответить с цитированием
Старый 06.06.2009, 07:28   #4
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию

Sazary, и как с этим бороться?
<= P.S. если я тебе помог нажми весы слева <=
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 09:37   #5
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию

все отловил! только я походу с виртуальной функцией накосячил... у меня в мейне вызывается всегда для базового класа функция Word()... Что изменить?
<= P.S. если я тебе помог нажми весы слева <=
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 10:42   #6
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию

все, справился и с этим
<= P.S. если я тебе помог нажми весы слева <=
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 10:51   #7
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию

вот что вышло
main.cpp
Код:
#include <iostream>
#include <fstream>
#include "Product.h"
using namespace std;
void error ( const char * file_name )
{             
cout << "\nCan't open " << file_name << '\n';
exit(1);
}
int main()
{
	Meat meat1;
	Fruit fruit1;
	Vegetable veg1;
	int t=0;
	char buf[100];	
	char*s1 = new char[20];
	char*s2 = new char[20];
	char*s3 = new char[20];
	char * s = new char [20];
	int s4 = 0;
	ifstream stream ("Ingridient.txt");    
	if (!stream) 
	{
		error ("Ingridient.txt");
	}
	while(!stream.eof())
	{
		stream.getline(buf,100,'\n');
		t++;
	}
	stream.close();
	ifstream stream2 ("Ingridient.txt");
	if (!stream2) 
	{
		error ("Ingridient.txt");
	}
	Product ** prod = new Product *[t];
	Dish dish(t);
	int i = 0;
	while (!stream2.eof())
	{ 
		stream2.getline(s1,20,' ');
		stream2.getline(s2,20,' ');
		stream2.getline(s3,20,' ');
		stream2.getline(s, 20,'\n');
		s4  = atoi(s);
		if(s1[0] == 'm')
		{
			Meat meat (s2,s3,s4); 
			meat1 = meat;
			prod[i] = &meat1;
			i++; 
		}
		if(s1[0] == 'f')
		{
			Fruit fruit (s2,s3,s4); 
			fruit1 = fruit;
			prod[i] = &fruit1;;
			i++;
		}
		if(s1[0] == 'v')
		{
			Vegetable veg (s2,s3,s4); 
			veg1 = veg;
			prod[i] = &veg1;
			i++;
		}
		s4 = 0;
	}	
	stream2.close();
	for(int j=0;j<t;j++)
	{
		dish += prod[j];
	}
	cout << "Result: \n" << dish;
	delete [] s1;
	delete [] s2;
	delete [] s3;
	system ("PAUSE");
	return 0;
}
String.h
Код:
#ifndef String_h
#define String_h
#include <iostream>
using namespace std;

class String 
{ 
private:
		int size;
		char *str;
public:
		String ();
		~String();
		String (const String & st);
		String & operator =(const String &st);
		String operator + (const String & st);
		String (const char * s);
		String & operator =(const char *st);
		String & operator += (const String & st);
		friend ostream &operator<<(ostream & stream, String &st);
};

#endif
<= P.S. если я тебе помог нажми весы слева <=
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 10:53   #8
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию

Product.h
Код:
#ifndef Product_h
#define Product_h
#include <iostream>
#include "String.h"
using namespace std;

class Product
{
protected:
    String name;
	int foodValue;
public:
	~Product();
	Product ();
	String & Isname ();
	int IsFoodValue();
	Product (const char * s2, int s4);
	virtual String Word ();
friend ostream &operator<<(ostream & stream, Product & st)
	{
		Product * d = &st;
		stream << st.name;
		stream << st.foodValue;
		stream<<d->Word();
		return stream;
	}
};
Product ::~Product()
{
	foodValue = 0;
}
String Product ::Word ()
{
	return name;
}
Product :: Product ()
{}
String & Product ::Isname ()
{
	return name;
}
int Product::IsFoodValue ()
{
	return foodValue;
}
Product::Product (const char * s2, int s4)
{
	name = s2;  
	this->foodValue = s4;
}
class Meat: public Product
{
private:
	String Type;
public:
	Meat ();
	Meat(const char * s2, const char * s3, int s4);
	Meat & operator = (const Meat & st);
	~Meat();	
	/*friend ostream &operator<<(ostream & stream, Meat & st)
	{
		stream << st.Type;
		stream << st.name;
		stream << st.foodValue;
		return stream;
	}*/
	String Word ();
};
Meat & Meat::operator = (const Meat & st)
{
	this->foodValue = st.foodValue;
	this->name = st.name;
	this->Type = st.Type;
	return (*this);
}
Meat::Meat ():Product()
{}
String Meat::Word()
{
	return Type;
}
Meat::~Meat()
{}
Meat::Meat(const char * s2, const char * s3, int s4):Product(s2,s4)
{
	this->Type = s3;
}
class Fruit: public Product
{
private:
	String Sweetness;
public:
	Fruit(const char * s2, const char * s3, int s4);
	Fruit & operator = (const Fruit & st);
	~Fruit();
	Fruit ();
	String  Word ();
};
Fruit & Fruit ::operator = (const Fruit & st)
{
	this->foodValue = st.foodValue;
	this->name = st.name;
	this->Sweetness = st.Sweetness;
	return (*this);
}
Fruit ::Fruit():Product()
{}
String  Fruit :: Word()
{
	return Sweetness;
}
Fruit::~Fruit()
{}
Fruit::Fruit(const char * s2, const char * s3, int s4):Product(s2,s4)
{
      this->Sweetness = s3;
}
class Vegetable: virtual public Product
{
private:
	String GrowingType;
public:
	Vegetable(const char * s2, const char * s3, int s4);
	Vegetable & operator = (const Vegetable & st);
	~Vegetable();
	Vegetable ();
	String Word ();
};
Vegetable & Vegetable::operator = (const Vegetable & st)
{
	this->foodValue = st.foodValue;
	this->name = st.name;
	this->GrowingType = st.GrowingType;
	return (*this);
}
String Vegetable::Word()
{
	return GrowingType;
}
Vegetable::Vegetable():Product()
{}
Vegetable::~Vegetable()
{}
Vegetable::Vegetable(const char * s2, const char * s3, int s4):Product(s2,s4)
{
	this->GrowingType = s3;
}
class Dish
{
private:
	String * name;
	int dfoodValue;
	int msize;
	static int p;
public:
	Dish(int a);
	friend ostream & operator <<(ostream & stream, Dish & dish);
	Dish & operator += (Product * prod);
};
int Dish::p = 0;
Dish & Dish:: operator += (Product * prod)
{
	String a(" ");
	Product * d = prod;
	dfoodValue += d->IsFoodValue();
	name[p] = d->Isname() + a + d->Word();
	p++;
	return (*this);
}

ostream & operator << (ostream & stream, Dish & dish)
{
	for(int i=0;i<dish.msize;i++)
	{
		stream << dish.name[i]<<'\n';
	}
	stream << dish.dfoodValue;
	return stream;
}
Dish::Dish(int a)
{
	name = new String [a];
	msize = a;
	dfoodValue = 0;
}
#endif
String.cpp
Код:
#include "String.h"
#include <iostream>
#include <string.h>
using namespace std;

String::~String()
{
	delete [] str;
}
String ::String()
{
	str = NULL;
	size = 0;
}
String::String (const String & st)
{
	size = st.size;
	if (str)
	{
		delete [] str;
	}
	str = new char [size];
	strcpy(str,st.str);
}
String String:: operator + (const String & st)
{
	String tmp = *this;
	tmp += st;
	return(tmp);
}
String& String::operator += (const String &st)
{
	char *tmp = new char [size];
	strcpy(tmp, str);
	if(str)
	{
		delete [] str;
	}
	size = st.size + size + 1;
	str = new char [size];
	strcpy(str, tmp);
	strcat(str, st.str);
	delete [] tmp;
	return(*this);
}
String & String::operator=(const String &st)
{
	this->size = st.size;
    if(str)
	{
		delete [] str;
	}
	str = new char [size];
	strcpy(str,st.str);
	return (*this);
}
String ::String(const char *s)
{
	size = strlen(s)+1;
	str = new char [size];
	strcpy(str,s);
}
String & String::operator = (const char *st)
{
	this->size=strlen(st)+1;
    if(str)
	{
		delete [] str;
	}
	str = new char [size];
	strcpy(str,st);
	return (*this);
}
ostream &operator<<(ostream& stream, String &st)
{
	stream << st.str;
	return stream;
}
<= P.S. если я тебе помог нажми весы слева <=
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 10:57   #9
assasin
Форумчанин
 
Регистрация: 27.04.2009
Сообщений: 123
По умолчанию

остался последний шаг! ошибка возникает в операторе += для Dish. а именно в строке name[p] = d->Isname() + a + d->Word(); почему? возможно в операторах String ошибка, но понять не могу в чем.
<= P.S. если я тебе помог нажми весы слева <=

Последний раз редактировалось assasin; 06.06.2009 в 11:30.
assasin вне форума Ответить с цитированием
Старый 06.06.2009, 14:23   #10
Sazary
В тени
Старожил
 
Аватар для Sazary
 
Регистрация: 19.12.2008
Сообщений: 5,788
По умолчанию

Что-то у меня вообще не компилится..
MinGW не нравится вот эта строчка в Product:
Код:
friend ostream &operator<<(ostream & stream, Product & st)
	{
		Product * d = &st;
		stream << st.name;
		stream << st.foodValue;
		stream<<d->Word();
		return stream;
	}
Цитата:
25 E:\Dev-Cpp\projects_3\Product.h no match for 'operator<<' in 'stream << **d->Product::_vptr$Product()'
---------
Билдер был более красноречив, и ругнулся еще и на String.h:
Код:
friend ostream& operator<<(ostream & stream, String &st);
Цитата:
Friends must be functions or classes
Declaration missing ;
Только вот что-то не могу понять, чего он хочет..
Вполне очевидно, чтобы что-то понять, необходимо книги читать.
Не нужно плодить бессмысленных тем. Вас Поиск избавит от многих проблем.

___________________________________ ___________________________________ _______
[=Правила форума=]_____[Поиск]_____[Литература по С++]____[Литература. Паскаль]
Sazary вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Не могу найти ошибку Tesmont Помощь студентам 2 20.05.2009 21:00
Не могу найти ошибку(С++) Yura_n Помощь студентам 8 20.01.2009 12:36
Не могу найти ошибку . KVANTOM Общие вопросы Delphi 2 08.01.2009 17:15
Как отловить ошибку в своей проге ??? Crazyman Win Api 8 02.09.2008 09:24
Не могу найти ошибку! Эдуард Общие вопросы C/C++ 7 27.02.2008 16:34