powered by simpleCommunicator - 2.0.59     © 2025 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / C++ [игнор отключен] [закрыт для гостей] / Создание класса шаблона, ассоциативного массива
2 сообщений из 2, страница 1 из 1
Создание класса шаблона, ассоциативного массива
    #38999649
The New Guy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
При компиляции возникают проблемы следующего характера.
1. В конструкторе IContainer компилятор пишет waring: преобразование const double в int возможна потеря данных, а потом и вовсе error: не найден оператор принимающий правый операнд хотя std::map вроде как позволяет так обращаться к элементам



Код: plaintext
1.
2.
3.
4.
IContainer<ElemType, IndexType>::IContainer(const ElemType & elem, const IndexType & index)
{
        arr[index]=elem;
}



2. В ф-ии GetElem несоответствие типов со знаком и без. строчка с return возвр. адреса локальной или временной переменной, тоже не ясно.



Код: plaintext
1.
2.
3.
4.
5.
6.
7.
const ElemType& IContainer<ElemType, IndexType>::GetElem(const IndexType & index)
{
    if(index>arr.size())
        std::cout<<"exception \n";
        throw ElemNotFound<IndexType> /*err */(index);
    return arr[index];
}



3. В PutElem преобразование const double в int возможна потеря


Код: plaintext
1.
2.
3.
4.
void IContainer<ElemType, IndexType>::PutElem(const IndexType& index, const ElemType& elem)
{
    arr.at(index)=elem; //??
}



4. Последнее, самое сложное не могут состыковаться блоки throw и catch я после слова throw создаю объект и хочу передать его в блок catch по ссылке, но он туда не лезет ни в какую, пробовал как мне кажется по всякому уже.


Код:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
throw ElemNotFound<IndexType> /*err */(index);
...
try
    {
    std::cout<<blablabla.GetElem(7)<<"  "<<obj.GetElem(1);
    }
    catch(/*ElemNotFound<IndexType>::*/ElemNotFound & bg/*...*/)
    {
        std::cout<<"exeption";//bg.mesg();
    }


Весь код:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
#include "stdafx.h"
#include <string>
#include <iostream>
#include <map>

template<class IndexType>
class ElemNotFound
{
private:
IndexType value;
public:
ElemNotFound(IndexType index):value(index){}
void mesg();
};
template<class IndexType>
void ElemNotFound<IndexType>::mesg()
{
std::cout<<"Element #"<<value<<" not found\n";
}


template <class ElemType, class IndexType> class IContainer
{
private:
std::map<ElemType, IndexType> arr;
public:
IContainer() {};
IContainer(const ElemType & elem, const IndexType & index);
virtual const ElemType& GetElem( const IndexType& index ) /*const throw ( ElemNotFound ) = 0*/;
virtual void PutElem( const IndexType& index, const ElemType& elem ) /*throw () = 0*/; //первый это номер элемента в массиве, второй сам элемент
};
template<class ElemType, class IndexType>
IContainer<ElemType, IndexType>::IContainer(const ElemType & elem, const IndexType & index)
{
arr[index]=elem;
}
template<class ElemType, class IndexType>
void IContainer<ElemType, IndexType>::PutElem(const IndexType& index, const ElemType& elem)
{
arr.at(index)=elem; //??
}
template<class ElemType, class IndexType>
const ElemType& IContainer<ElemType, IndexType>::GetElem(const IndexType & index)
{
if(index>arr.size())
std::cout<<"exception \n";
throw ElemNotFound<IndexType> /*err */(index);
return arr[index];
}

int main()
{
IContainer<double, int> obj (5, 7);
IContainer<std::string, int> blablabla("golden joe", 6);
blablabla.PutElem(4, "duck");
/*IContainer<double, std::string> c;
c.PutElem("pi", 3.14);
c.PutElem("e", 2.71);
std::cout << c.GetElem("pi")<<"\n";*/
try
{
std::cout<<blablabla.GetElem(7)<<" "<<obj.GetElem(1);
}
catch(/*ElemNotFound<IndexType>::*/ElemNotFound & bg/*...*/)
{
std::cout<<"exeption";//bg.mesg();
}
return 0; 
}


Народ хочет разобраться что к чему, дело для нас новое, не освоенное! С СТЛ и Exception-ами сталкиваюсь впервые, строго не судите!!
...
Рейтинг: 0 / 0
Создание класса шаблона, ассоциативного массива
    #38999650
Dimitry Sibiryakov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
The New GuyС СТЛ и Exception-ами сталкиваюсь впервые
Ага, то есть доку не открывал и то, что у std::map первый параметр это ключ, а не
значение, тебя не смущает?..
Posted via ActualForum NNTP Server 1.5
...
Рейтинг: 0 / 0
2 сообщений из 2, страница 1 из 1
Форумы / C++ [игнор отключен] [закрыт для гостей] / Создание класса шаблона, ассоциативного массива
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]