Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.87/15: Рейтинг темы: голосов - 15, средняя оценка - 4.87
1 / 1 / 1
Регистрация: 20.09.2014
Сообщений: 310

Как правильно реализовать обобщённый класс?

14.05.2016, 19:42. Показов 3182. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
хочу создать класс
C++
1
class MyGenericClass<T>
Ругается на эту T. убрать не вариант,нужна дальше
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
14.05.2016, 19:42
Ответы с готовыми решениями:

Как правильно реализовать класс?
Вопрос первый при реализации классов на java, я для каждого класса создавал новый файл, как это лучше реализовать в c++ есть ли возможность...

Как правильно реализовать полиморфизм?
Имеется такая иерархия классов //classes.h class CL1 { private: int x; virtual char c;

Как правильно реализовать множественное наследование?
Всем привет. Нужна помощь. Вот смотрите. Имеется простой класс. От него порождаются два класса-наследника. А от этих двух классов...

9
1373 / 596 / 199
Регистрация: 02.08.2011
Сообщений: 2,886
14.05.2016, 20:07
Лучший ответ Сообщение было отмечено tezaurismosis как решение

Решение

C++
1
2
3
4
5
template <typename T>
class MyGenericClass
{
    T x;
};
0
1 / 1 / 1
Регистрация: 20.09.2014
Сообщений: 310
14.05.2016, 20:11  [ТС]
ясно. спасибо)
теперь другая ошика)

C++
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#include <iostream>
#include <conio.h>
#include <math.h>
 
using namespace std;
 
template <typename T>
class MyGenericClass
{
    T[] aa;
    int index = 0;
    public MyGenericClass(int q)
    {
        aa = new T[q];
    }
    public MyGenericClass(MyGenericClass<T> q)
    {
        aa = q.aa;
    }
    public void ArrayAdd(T value)
    {
        aa[index++] = value;
    }
    public int GetLength()
    {
        return aa.Length;
    }
    public void ArrayResize(int newSize)
    {
        if (newSize < aa.Length)
        {
            Console.WriteLine("Error!!!");
        }
        else
        {
            Array.Resize(ref aa, newSize);
        }
    }
    public void ArrayClear()
    {
        for (int i = 0; i < aa.Length; i++)
        {
            aa[i] = default(T);
        }
    }
    public void Show()
    {
        foreach(T item in aa)
        {
            Console.WriteLine(" " + item + " ");
        }
    }
    public T GetElement(int qwe)
    {
        return aa[qwe];
    }
}
class Program
{
    static void Main(string[] args)
    {
        string prov = "";
        int index = 0;
        MyGenericClass<string> a1 = null;
        MyGenericClass<int> a2 = null;
        MyGenericClass<double> a3 = null;
        MyGenericClass<char> a4 = null;
        string control = "";
        while (control != "ex")
        {
            Console.WriteLine("1 - Create Array *");
            Console.WriteLine("2 - Get Lenght Array *");
            Console.WriteLine("3 - Get Element *");
            Console.WriteLine("4 - Resize Array *");
            Console.WriteLine("5 - Clear Array *");
            Console.WriteLine("6 - Copy Array *");
            Console.WriteLine("*************************");
            control = Console.ReadLine();
            Console.Clear();
            switch (control)
            {
            case "1":
                Console.WriteLine("What array create? string,int,double,char?");
                string s_c = Console.ReadLine();
                prov = s_c;
                if (s_c == "string")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a1 = new MyGenericClass<string>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a1.ArrayAdd(Console.ReadLine());
                    }
                }
                if (s_c == "int")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a2 = new MyGenericClass<int>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(int.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "double")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a3 = new MyGenericClass<double>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a3.ArrayAdd(double.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "char")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a4 = new MyGenericClass<char>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(char.Parse(Console.ReadLine()));
                    }
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "2":
                if (prov == "string")
                {
                    Console.WriteLine(a1.GetLength());
                }
                if (prov == "int")
                {
                    Console.WriteLine(a2.GetLength());
                }
                if (prov == "double")
                {
                    Console.WriteLine(a3.GetLength());
                }
                if (prov == "char")
                {
                    Console.WriteLine(a4.GetLength());
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "3":
                if (prov == "string")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a1.GetElement(ind_dost - 1));
                }
                if (prov == "int")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a2.GetElement(ind_dost - 1));
                }
                if (prov == "double")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a3.GetElement(ind_dost - 1));
                }
                if (prov == "char")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a4.GetElement(ind_dost - 1));
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "4":
                if (prov == "string")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a1.ArrayResize(new_size);
                }
                if (prov == "int")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a2.ArrayResize(new_size);
                }
                if (prov == "double")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a3.ArrayResize(new_size);
                }
                if (prov == "char")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a4.ArrayResize(new_size);
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "5":
                if (prov == "string")
                {
                    a1.ArrayClear();
                }
                if (prov == "int")
                {
                    a2.ArrayClear();
                }
                if (prov == "double")
                {
                    a3.ArrayClear();
                }
                if (prov == "char")
                {
                    a4.ArrayClear();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "6":
                if (prov == "string")
                {
                    MyGenericClass<string> copy_a1 = new MyGenericClass<string>(a1);
                    copy_a1.Show();
                }
                if (prov == "int")
                {
                    MyGenericClass<int> copy_a2 = new MyGenericClass<int>(a2);
                    copy_a2.Show();
                }
                if (prov == "double")
                {
                    MyGenericClass<double> copy_a3 = new MyGenericClass<double>(a3);
                    copy_a3.Show();
                }
                if (prov == "char")
                {
                    MyGenericClass<char> copy_a4 = new MyGenericClass<char>(a4);
                    copy_a4.Show();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            }
        }
    }
}
перед class Program пишет требуется ;
0
1373 / 596 / 199
Регистрация: 02.08.2011
Сообщений: 2,886
14.05.2016, 20:12
T a[];
0
1 / 1 / 1
Регистрация: 20.09.2014
Сообщений: 310
14.05.2016, 20:19  [ТС]
Цитата Сообщение от daslex Посмотреть сообщение
T a[];
это куда?
0
1373 / 596 / 199
Регистрация: 02.08.2011
Сообщений: 2,886
14.05.2016, 20:33
Дайте актуальный код. Вы стёрли то, где написано было T[] a;
Цитата Сообщение от Андей Посмотреть сообщение
перед class Program пишет требуется ;
поставьте ; сразу после закрывающей скобки, которая идёт сразу перед этим классом. Закрывающей! Перед!
0
1 / 1 / 1
Регистрация: 20.09.2014
Сообщений: 310
14.05.2016, 20:43  [ТС]
C++
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#include <iostream>
#include <conio.h>
#include <math.h>
 
using namespace std;
 
template <typename T>
class MyGenericClass
{
    T[] aa;
    int index = 0;
    public MyGenericClass(int q)
    {
        aa = new T[q];
    }
    public MyGenericClass(MyGenericClass<T> q)
    {
        aa = q.aa;
    }
    public void ArrayAdd(T value)
    {
        aa[index++] = value;
    }
    public int GetLength()
    {
        return aa.Length;
    }
    public void ArrayResize(int newSize)
    {
        if (newSize < aa.Length)
        {
            Console.WriteLine("Error!!!");
        }
        else
        {
            Array.Resize(ref aa, newSize);
        }
    }
    public void ArrayClear()
    {
        for (int i = 0; i < aa.Length; i++)
        {
            aa[i] = default(T);
        }
    }
    public void Show()
    {
        foreach(T item in aa)
        {
            Console.WriteLine(" " + item + " ");
        }
    }
    public T GetElement(int qwe)
    {
        return aa[qwe];
    }
}
class Program
{
    static void Main(string[] args)
    {
        string prov = "";
        int index = 0;
        MyGenericClass<string> a1 = null;
        MyGenericClass<int> a2 = null;
        MyGenericClass<double> a3 = null;
        MyGenericClass<char> a4 = null;
        string control = "";
        while (control != "ex")
        {
            Console.WriteLine("1 - Create Array *");
            Console.WriteLine("2 - Get Lenght Array *");
            Console.WriteLine("3 - Get Element *");
            Console.WriteLine("4 - Resize Array *");
            Console.WriteLine("5 - Clear Array *");
            Console.WriteLine("6 - Copy Array *");
            Console.WriteLine("*************************");
            control = Console.ReadLine();
            Console.Clear();
            switch (control)
            {
            case "1":
                Console.WriteLine("What array create? string,int,double,char?");
                string s_c = Console.ReadLine();
                prov = s_c;
                if (s_c == "string")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a1 = new MyGenericClass<string>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a1.ArrayAdd(Console.ReadLine());
                    }
                }
                if (s_c == "int")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a2 = new MyGenericClass<int>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(int.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "double")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a3 = new MyGenericClass<double>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a3.ArrayAdd(double.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "char")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a4 = new MyGenericClass<char>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(char.Parse(Console.ReadLine()));
                    }
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "2":
                if (prov == "string")
                {
                    Console.WriteLine(a1.GetLength());
                }
                if (prov == "int")
                {
                    Console.WriteLine(a2.GetLength());
                }
                if (prov == "double")
                {
                    Console.WriteLine(a3.GetLength());
                }
                if (prov == "char")
                {
                    Console.WriteLine(a4.GetLength());
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "3":
                if (prov == "string")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a1.GetElement(ind_dost - 1));
                }
                if (prov == "int")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a2.GetElement(ind_dost - 1));
                }
                if (prov == "double")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a3.GetElement(ind_dost - 1));
                }
                if (prov == "char")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a4.GetElement(ind_dost - 1));
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "4":
                if (prov == "string")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a1.ArrayResize(new_size);
                }
                if (prov == "int")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a2.ArrayResize(new_size);
                }
                if (prov == "double")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a3.ArrayResize(new_size);
                }
                if (prov == "char")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a4.ArrayResize(new_size);
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "5":
                if (prov == "string")
                {
                    a1.ArrayClear();
                }
                if (prov == "int")
                {
                    a2.ArrayClear();
                }
                if (prov == "double")
                {
                    a3.ArrayClear();
                }
                if (prov == "char")
                {
                    a4.ArrayClear();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "6":
                if (prov == "string")
                {
                    MyGenericClass<string> copy_a1 = new MyGenericClass<string>(a1);
                    copy_a1.Show();
                }
                if (prov == "int")
                {
                    MyGenericClass<int> copy_a2 = new MyGenericClass<int>(a2);
                    copy_a2.Show();
                }
                if (prov == "double")
                {
                    MyGenericClass<double> copy_a3 = new MyGenericClass<double>(a3);
                    copy_a3.Show();
                }
                if (prov == "char")
                {
                    MyGenericClass<char> copy_a4 = new MyGenericClass<char>(a4);
                    copy_a4.Show();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            }
        }
    }
}
0
1373 / 596 / 199
Регистрация: 02.08.2011
Сообщений: 2,886
14.05.2016, 21:00
Не знаю, что там ещё, поэтому не могу сказать. Внутри первого по Вашему, внутри второго с исправлениями с бОльшими.
Тут оно много где чего написать обязано.

Кликните здесь для просмотра всего текста
C++
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#include <iostream>
#include <conio.h>
#include <math.h>
 
using namespace std;
 
template <typename T>
class MyGenericClass
{
    T[] aa;
    int index = 0;
    public MyGenericClass(int q)
    {
        aa = new T[q];
    }
    public MyGenericClass(MyGenericClass<T> q)
    {
        aa = q.aa;
    }
    public void ArrayAdd(T value)
    {
        aa[index++] = value;
    }
    public int GetLength()
    {
        return aa.Length;
    }
    public void ArrayResize(int newSize)
    {
        if (newSize < aa.Length)
        {
            Console.WriteLine("Error!!!");
        }
        else
        {
            Array.Resize(ref aa, newSize);
        }
    }
    public void ArrayClear()
    {
        for (int i = 0; i < aa.Length; i++)
        {
            aa[i] = default(T);
        }
    }
    public void Show()
    {
        foreach(T item in aa)
        {
            Console.WriteLine(" " + item + " ");
        }
    }
    public T GetElement(int qwe)
    {
        return aa[qwe];
    }
}; //<--- ИСПРАВЛЕНО
class Program
{
    static void Main(string[] args)
    {
        string prov = "";
        int index = 0;
        MyGenericClass<string> a1 = null;
        MyGenericClass<int> a2 = null;
        MyGenericClass<double> a3 = null;
        MyGenericClass<char> a4 = null;
        string control = "";
        while (control != "ex")
        {
            Console.WriteLine("1 - Create Array *");
            Console.WriteLine("2 - Get Lenght Array *");
            Console.WriteLine("3 - Get Element *");
            Console.WriteLine("4 - Resize Array *");
            Console.WriteLine("5 - Clear Array *");
            Console.WriteLine("6 - Copy Array *");
            Console.WriteLine("*************************");
            control = Console.ReadLine();
            Console.Clear();
            switch (control)
            {
            case "1":
                Console.WriteLine("What array create? string,int,double,char?");
                string s_c = Console.ReadLine();
                prov = s_c;
                if (s_c == "string")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a1 = new MyGenericClass<string>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a1.ArrayAdd(Console.ReadLine());
                    }
                }
                if (s_c == "int")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a2 = new MyGenericClass<int>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(int.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "double")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a3 = new MyGenericClass<double>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a3.ArrayAdd(double.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "char")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a4 = new MyGenericClass<char>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(char.Parse(Console.ReadLine()));
                    }
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "2":
                if (prov == "string")
                {
                    Console.WriteLine(a1.GetLength());
                }
                if (prov == "int")
                {
                    Console.WriteLine(a2.GetLength());
                }
                if (prov == "double")
                {
                    Console.WriteLine(a3.GetLength());
                }
                if (prov == "char")
                {
                    Console.WriteLine(a4.GetLength());
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "3":
                if (prov == "string")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a1.GetElement(ind_dost - 1));
                }
                if (prov == "int")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a2.GetElement(ind_dost - 1));
                }
                if (prov == "double")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a3.GetElement(ind_dost - 1));
                }
                if (prov == "char")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a4.GetElement(ind_dost - 1));
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "4":
                if (prov == "string")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a1.ArrayResize(new_size);
                }
                if (prov == "int")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a2.ArrayResize(new_size);
                }
                if (prov == "double")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a3.ArrayResize(new_size);
                }
                if (prov == "char")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a4.ArrayResize(new_size);
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "5":
                if (prov == "string")
                {
                    a1.ArrayClear();
                }
                if (prov == "int")
                {
                    a2.ArrayClear();
                }
                if (prov == "double")
                {
                    a3.ArrayClear();
                }
                if (prov == "char")
                {
                    a4.ArrayClear();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "6":
                if (prov == "string")
                {
                    MyGenericClass<string> copy_a1 = new MyGenericClass<string>(a1);
                    copy_a1.Show();
                }
                if (prov == "int")
                {
                    MyGenericClass<int> copy_a2 = new MyGenericClass<int>(a2);
                    copy_a2.Show();
                }
                if (prov == "double")
                {
                    MyGenericClass<double> copy_a3 = new MyGenericClass<double>(a3);
                    copy_a3.Show();
                }
                if (prov == "char")
                {
                    MyGenericClass<char> copy_a4 = new MyGenericClass<char>(a4);
                    copy_a4.Show();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            }
        }
    }
}
0
1373 / 596 / 199
Регистрация: 02.08.2011
Сообщений: 2,886
14.05.2016, 21:00
Кликните здесь для просмотра всего текста
C++
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#include <iostream>
#include <conio.h>
#include <math.h>
 
using namespace std;
 
template <typename T>
class MyGenericClass
{
    T aa[];
    int index = 0;
    public: MyGenericClass(int q)
    {
        aa = new T[q];
    }
    public: MyGenericClass(MyGenericClass<T&> q)
    {
        aa = q.aa;
    }
    public: void ArrayAdd(T value)
    {
        aa[index++] = value;
    }
    public: int GetLength()
    {
        return aa.Length;
    }
    public: void ArrayResize(int newSize)
    {
        if (newSize < aa.Length)
        {
            cerr << "Error!!!";
           // Console.WriteLine("Error!!!");
        }
        else
        {
            Array.Resize(ref aa, newSize);
        }
    }
    public: void ArrayClear()
    {
        for (int i = 0; i < aa.Length; i++)
        {
            aa[i] = default(T);
        }
    }
    public: void Show()
    {
        foreach(T item in aa)
        {
            Console.WriteLine(" " + item + " ");
        }
    }
    public: T GetElement(int qwe)
    {
        return aa[qwe];
    }
};
 
class Program
{
    static void Main(string[] args)
    {
        string prov = "";
        int index = 0;
        MyGenericClass<string> a1 = null;
        MyGenericClass<int> a2 = null;
        MyGenericClass<double> a3 = null;
        MyGenericClass<char> a4 = null;
        string control = "";
        while (control != "ex")
        {
            Console.WriteLine("1 - Create Array *");
            Console.WriteLine("2 - Get Lenght Array *");
            Console.WriteLine("3 - Get Element *");
            Console.WriteLine("4 - Resize Array *");
            Console.WriteLine("5 - Clear Array *");
            Console.WriteLine("6 - Copy Array *");
            Console.WriteLine("*************************");
            control = Console.ReadLine();
            Console.Clear();
            switch (control)
            {
            case "1":
                Console.WriteLine("What array create? string,int,double,char?");
                string s_c = Console.ReadLine();
                prov = s_c;
                if (s_c == "string")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a1 = new MyGenericClass<string>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a1.ArrayAdd(Console.ReadLine());
                    }
                }
                if (s_c == "int")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a2 = new MyGenericClass<int>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(int.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "double")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a3 = new MyGenericClass<double>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a3.ArrayAdd(double.Parse(Console.ReadLine()));
                    }
                }
                if (s_c == "char")
                {
                    Console.Write("Enter array lenght: ");
                    index = int.Parse(Console.ReadLine());
                    a4 = new MyGenericClass<char>(index);
                    for (int i = 0; i < index; i++)
                    {
                        a2.ArrayAdd(char.Parse(Console.ReadLine()));
                    }
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "2":
                if (prov == "string")
                {
                    Console.WriteLine(a1.GetLength());
                }
                if (prov == "int")
                {
                    Console.WriteLine(a2.GetLength());
                }
                if (prov == "double")
                {
                    Console.WriteLine(a3.GetLength());
                }
                if (prov == "char")
                {
                    Console.WriteLine(a4.GetLength());
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "3":
                if (prov == "string")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a1.GetElement(ind_dost - 1));
                }
                if (prov == "int")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a2.GetElement(ind_dost - 1));
                }
                if (prov == "double")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a3.GetElement(ind_dost - 1));
                }
                if (prov == "char")
                {
                    Console.Write("Enter index : ");
                    int ind_dost = int.Parse(Console.ReadLine());
                    Console.WriteLine(a4.GetElement(ind_dost - 1));
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "4":
                if (prov == "string")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a1.ArrayResize(new_size);
                }
                if (prov == "int")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a2.ArrayResize(new_size);
                }
                if (prov == "double")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a3.ArrayResize(new_size);
                }
                if (prov == "char")
                {
                    Console.Write("Enter new size : ");
                    int new_size = int.Parse(Console.ReadLine());
                    a4.ArrayResize(new_size);
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "5":
                if (prov == "string")
                {
                    a1.ArrayClear();
                }
                if (prov == "int")
                {
                    a2.ArrayClear();
                }
                if (prov == "double")
                {
                    a3.ArrayClear();
                }
                if (prov == "char")
                {
                    a4.ArrayClear();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            case "6":
                if (prov == "string")
                {
                    MyGenericClass<string> copy_a1 = new MyGenericClass<string>(a1);
                    copy_a1.Show();
                }
                if (prov == "int")
                {
                    MyGenericClass<int> copy_a2 = new MyGenericClass<int>(a2);
                    copy_a2.Show();
                }
                if (prov == "double")
                {
                    MyGenericClass<double> copy_a3 = new MyGenericClass<double>(a3);
                    copy_a3.Show();
                }
                if (prov == "char")
                {
                    MyGenericClass<char> copy_a4 = new MyGenericClass<char>(a4);
                    copy_a4.Show();
                }
                Console.ReadKey();
                Console.Clear();
                break;
            }
        }
    }
}
0
14.05.2016, 21:07

Не по теме:

C# → C++

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
14.05.2016, 21:07
Помогаю со студенческими работами здесь

Как реализовать класс Dictionary?
Карточка иностранного слова представляет собой структуру, содержащую иностранное слово и его перевод. Для моделирования электронного...

Как правильно реализовать инициализацию массива функцией?
Здравствуйте! Мне нужно что бы вся инициализация массива происходила в отдельной функции и что бы этот массив можно было в дальнейшем...

Реализовать класс char_queue как связанный список и как вектор
Добрый день. Дано задание: реализовать класс char_queue как связанный список и как вектор. Данный язык программирования для меня...

Как реализовать данный абстрактный класс?
Создать абстрактный класс Function с методом вычисления значения функции y=f(x) в заданной точке. Создать производные классы: Line...

Как правильно реализовать чтение данных из текстового файла?
char buff; ifstream sho; sho.open(&quot;Мафіни.txt&quot;); if (!sho.is_open()) { cout &lt;&lt; &quot;Error!!!\n&quot;; } else { cout &lt;&lt;...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Основы отладки веб-приложений на SDL3 по USB и Wi-Fi, запущенных в браузере мобильных устройств
8Observer8 07.02.2026
Содержание блога Браузер Chrome имеет средства для отладки мобильных веб-приложений по USB. В этой пошаговой инструкции ограничимся работой с консолью. Вывод в консоль - это часть процесса. . .
SDL3 для Web (WebAssembly): Обработчик клика мыши в браузере ПК и касания экрана в браузере на мобильном устройстве
8Observer8 02.02.2026
Содержание блога Для начала пошагово создадим рабочий пример для подготовки к экспериментам в браузере ПК и в браузере мобильного устройства. Потом напишем обработчик клика мыши и обработчик. . .
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования. Часть библиотеки BedvitCOM Использованы. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru