Форум программистов, компьютерный форум, киберфорум
C++ Builder
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.94/18: Рейтинг темы: голосов - 18, средняя оценка - 4.94
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106

Ошибка при комилировании. Cannot use template 'texnika<T>' without specifying specialization parameters

17.01.2014, 15:25. Показов 3674. Ответов 16
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Выходит вот такая ошибка:

Code
1
2
[C++ Error] Unit1.cpp(34): E2102 Cannot use template 'texnika<T>' without specifying specialization parameters
[C++ Error] Unit1.cpp(34): E2040 Declaration terminated incorrectly
Вот собственно сама программа
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
//---------------------------------------------------------------------------
 
#include <vcl.h>
#include <comobj.hpp>
#include <Grids.hpp>
#include <stdlib.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
 
template <class T>
class texnika
{
char *name;
int zena;
int colichestvo;
int garantia;
AnsiString strana;
 
public: void init(char *n, int z, int c, int g, AnsiString s);
int sravn(int z);
void print(TStringGrid *Stringgrid1, int n);
void prisv(const texnika<T> &t);
texnika();
texnika(char *n, int z, int c, int g, AnsiString s);
texnika(const texnika<T> &t);
~texnika() {delete[] name;};
texnika<T> &operator = (const texnika<T> &t);
friend bool operator == (const texnika<T> &t, int z);
};
 
texnika s[30], f[30], s1[30];
 
TForm1 *Form1;
//---------------------------------------------------------------------------
template <class T>
void texnika<T>::prisv(const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
garantia = t.garantia;
colichestvo = t.colichestvo;
strana = t.strana;}
 
template <class T>
void texnika<T>::init(char *n, int z, int c, int g, AnsiString s)
{
name = new char [strlen(n) + 1];
strcpy(name, n);
zena = z;
colichestvo = c;
garantia = g;
strana = s;}
 
template <class T>
int texnika<T>::sravn(int z)
{
if(zena == z)
return 0;
else return 1;
}
 
template <class T>
void texnika<T>::print(TStringGrid *StringGrid1, int n)
{
StringGrid1 -> Cells[1][n] = name;
StringGrid1 -> Cells[2][n] = zena;
StringGrid1 -> Cells[3][n] = colichestvo;
StringGrid1 -> Cells[4][n] = garantia;
StringGrid1 -> Cells[5][n] = strana;
}
 
template <class T>
texnika<T>::texnika()
{
name = "Название";
strcpy(name, "Название");
zena = 0;
colichestvo = 0;
garantia = 0;
strana = "Китай";
}
 
template <class T>
texnika<T>::texnika(char *n, int z, int c, int g, AnsiString s)
{
name = new char [strlen(n) + 1];
strcpy(name, n);
zena = z;
colichestvo = c;
garantia = g;
strana = s;
}
 
template <class T>
texnika<T>::texnika(const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
garantia = t.garantia;
colichestvo = t.colichestvo;
strana = t.strana;
}
 
template <class T>
texnika<T> &texnika<T>::operator = (const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
garantia = t.garantia;
colichestvo = t.colichestvo;
strana = t.strana;
return *this;
}
 
template <class T>
bool operator == (const texnika<T> &t, int z)
{
return t.zena == z;
}
 
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
StringGrid1 -> RowCount = 7;
StringGrid1 -> ColCount = 6;
StringGrid1 -> Cells[1][0] = "Название";
StringGrid1 -> Cells[2][0] = "Цена, руб";
StringGrid1 -> Cells[3][0] = "Количество";
StringGrid1 -> Cells[4][0] = "Гарантия, лет";
StringGrid1 -> Cells[5][0] = "Страна";
StringGrid2 -> Cells[1][0] = "Название";
StringGrid2 -> Cells[2][0] = "Цена, руб";
StringGrid2 -> Cells[3][0] = "Количество";
StringGrid2 -> Cells[4][0] = "Гарантия, лет";
StringGrid2 -> Cells[5][0] = "Страна";
for(int i = 1; i < 21; i++)
{
        StringGrid1 -> Cells[0][i] = StrToInt(i);
}
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Variant var_Excel, var_Sheet;
int Row_Counter = 0, Column_Counter = 0, Max_Column = 5, Max_Row = 7;
WideString p;
p = Edit1 -> Text;
var_Excel = CreateOleObject("Excel.Application");
var_Excel.OlePropertyGet("Application").OlePropertyGet("Workbooks").OleProcedure("Open", p);
var_Excel.OlePropertySet("Visible", false);
var_Sheet = var_Excel.OlePropertyGet("ActiveSheet");
 
for (Row_Counter; Row_Counter <= Max_Row; Row_Counter++)
{
        for (Column_Counter; Column_Counter <= Max_Column ; Column_Counter++)
        {
                StringGrid1 -> Cells[Column_Counter + 1][Row_Counter + 1] =
                var_Sheet.OlePropertyGet("Cells").OlePropertyGet("Item", Row_Counter + 1, Column_Counter + 1);
        }
        Column_Counter = 0;
}
 
var_Excel.OlePropertyGet("Application").OleProcedure("Quit");
var_Sheet = Unassigned;
var_Excel = Unassigned;
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button2Click(TObject *Sender)
{AnsiString a, e;
int b, c, d;
int n, k;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        a = StringGrid1 -> Cells[1][i];
        b = StrToInt(StringGrid1 -> Cells[2][i]);
        c = StrToInt(StringGrid1 -> Cells[3][i]);
        d = StrToInt(StringGrid1 -> Cells[4][i]);
        e = StringGrid1 -> Cells[5][i];
        char * astr = a.c_str();
        s[i].init(astr, b, c, d, e);
}
k = StrToInt(Edit2 -> Text);
for(int i = 1;i < n; i++)
{
        if(s[i] == k)
        {
                s[i].print(StringGrid2, 1);
        }
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
int b, c, d;
AnsiString a, e;
int i;
i = StrToInt(Edit8 -> Text);
a = Edit3 -> Text;
b = StrToInt(Edit4 -> Text);
c = StrToInt(Edit5 -> Text);
d = StrToInt(Edit6 -> Text);
e = Edit7 -> Text;
char * astr = a.c_str();
f[i].init(astr, b, c, d, e);
f[i].print(StringGrid1, i);
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button5Click(TObject *Sender)
{
if (!OpenDialog1 -> Execute()) return;
AnsiString  list;
 
list = OpenDialog1 -> FileName;
Edit1 -> Text = list;
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button6Click(TObject *Sender)
{
WideString str;
TStringList *sl = new TStringList;
for(int i = 1 ; i < StringGrid1 -> RowCount; ++i)
{
        for(int j = 1; j < StringGrid1 -> ColCount; ++j)
        str += StringGrid1 -> Cells[j][i] + "\t";
        sl -> Add(Trim(str));
        str = "\n\r" ;
}
 
if (SaveDialog1 -> Execute())
sl -> SaveToFile(SaveDialog1 -> FileName);
delete sl;
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button7Click(TObject *Sender)
{
for(int i = 0; i < 30; i++)
{
        s[i].~texnika();
        f[i].~texnika();
        s1[i].~texnika();
}
Close();
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button8Click(TObject *Sender)
{
int n;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        s1[i].operator = (s[i]);
        s1[i].print(StringGrid2, i);
}
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button9Click(TObject *Sender)
{
for(int i = 0; i < StringGrid2 -> RowCount; i++)
StringGrid2 -> Rows[i] -> Clear();
 
StringGrid2 -> Cells[1][0] = "Название";
StringGrid2 -> Cells[2][0] = "Цена, руб";
StringGrid2 -> Cells[3][0] = "Количество";
StringGrid2 -> Cells[4][0] = "Гарантия, лет";
StringGrid2 -> Cells[5][0] = "Страна";
for(int i = 1; i < 21; i++)
{
        StringGrid2 -> Cells[0][i] = StrToInt(i);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
for(int i = 0; i < StringGrid1 -> RowCount; i++)
StringGrid1 -> Rows[i] -> Clear();
 
StringGrid1 -> Cells[1][0] = "Название";
StringGrid1 -> Cells[2][0] = "Цена, руб";
StringGrid1 -> Cells[3][0] = "Количество";
StringGrid1 -> Cells[4][0] = "Гарантия, лет";
StringGrid1 -> Cells[5][0] = "Страна";
for(int i = 1; i < 21; i++)
{
        StringGrid1 -> Cells[0][i] = StrToInt(i);
}
}
//---------------------------------------------------------------------------
Как исправить?
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
17.01.2014, 15:25
Ответы с готовыми решениями:

CBuilder XE Cannot use template 'multiset<_Kty,_Pr,_Alloc>' without specifying specialization parameters F
Unit1.cpp(32): E2102 Cannot use template 'multiset&lt;_Kty,_Pr,_Alloc&gt;' without specifying specialization parameters Full parser context ...

Ошибка компиляции: template-id does not match any template declaration
Здравствуйте. Помогите, пожалуйста: #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; T maxn(T*, const int*); ...

Template definition of non-template при использовании частичной спецификации шаблонов
Всем привет! Есть задача написать шаблон класса, принимающего в качестве параметров типа шаблон и некоторый тип. Собственно, вот код: ...

16
162 / 162 / 42
Регистрация: 29.05.2010
Сообщений: 435
17.01.2014, 15:51
Нужно указать тип здесь, какой Вам нужен, например int
C++
1
texnika<int> s[30], f[30], s1[30];
1
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106
17.01.2014, 17:03  [ТС]
Цитата Сообщение от AnDrew_LP Посмотреть сообщение
Нужно указать тип здесь, какой Вам нужен, например int
C++
1
texnika<int> s[30], f[30], s1[30];
Теперь выдает такую

[C++ Error] Unit1.cpp(250): E2045 Destructor name must match the class name
[C++ Error] Unit1.cpp(251): E2045 Destructor name must match the class name
[C++ Error] Unit1.cpp(252): E2045 Destructor name must match the class name

Добавлено через 47 минут
Так, эту ошибку я исправил, но теперь появилась такая
[Linker Error] Unresolved external 'operator ==(const texnika<int>&, int)' referenced from C:\PROGRAM FILES\BORLAND\CBUILDER6\PROJECTS\UNIT1.O BJ


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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//---------------------------------------------------------------------------
 
#include <vcl.h>
#include <comobj.hpp>
#include <Grids.hpp>
#include <stdlib.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
 
template <class T>
class texnika
{
char *name;
int zena;
int colichestvo;
int garantia;
AnsiString strana;
 
public: void init(char *n, int z, int c, int g, AnsiString s);
int sravn(int z);
void print(TStringGrid *Stringgrid1, int n);
void prisv(const texnika &t);
texnika();
texnika(char *n, int z, int c, int g, AnsiString s);
texnika(const texnika &t);
~texnika() {delete[] name;};
texnika &operator = (const texnika &t);
friend bool operator == (const texnika &t, int z);
};
 
texnika<int> s[30], f[30], s1[30];
 
TForm1 *Form1;
//---------------------------------------------------------------------------
template <class T>
void texnika<T>::prisv(const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
garantia = t.garantia;
colichestvo = t.colichestvo;
strana = t.strana;}
 
template <class T>
void texnika<T>::init(char *n, int z, int c, int g, AnsiString s)
{
name = new char [strlen(n) + 1];
strcpy(name, n);
zena = z;
colichestvo = c;
garantia = g;
strana = s;}
 
template <class T>
int texnika<T>::sravn(int z)
{
if(zena == z)
return 0;
else return 1;
}
 
template <class T>
void texnika<T>::print(TStringGrid *StringGrid1, int n)
{
StringGrid1 -> Cells[1][n] = name;
StringGrid1 -> Cells[2][n] = zena;
StringGrid1 -> Cells[3][n] = colichestvo;
StringGrid1 -> Cells[4][n] = garantia;
StringGrid1 -> Cells[5][n] = strana;
}
 
template <class T>
texnika<T>::texnika()
{
name = "Название";
strcpy(name, "Название");
zena = 0;
colichestvo = 0;
garantia = 0;
strana = "Китай";
}
 
template <class T>
texnika<T>::texnika(char *n, int z, int c, int g, AnsiString s)
{
name = new char [strlen(n) + 1];
strcpy(name, n);
zena = z;
colichestvo = c;
garantia = g;
strana = s;
}
 
template <class T>
texnika<T>::texnika(const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
garantia = t.garantia;
colichestvo = t.colichestvo;
strana = t.strana;
}
 
template <class T>
texnika<T> &texnika<T>::operator = (const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
garantia = t.garantia;
colichestvo = t.colichestvo;
strana = t.strana;
return *this;
}
 
template <class T>
bool operator == (const texnika<T> &t, int z)
{
return t.zena == z;
}
 
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
StringGrid1 -> RowCount = 7;
StringGrid1 -> ColCount = 6;
StringGrid1 -> Cells[1][0] = "Название";
StringGrid1 -> Cells[2][0] = "Цена, руб";
StringGrid1 -> Cells[3][0] = "Количество";
StringGrid1 -> Cells[4][0] = "Гарантия, лет";
StringGrid1 -> Cells[5][0] = "Страна";
StringGrid2 -> Cells[1][0] = "Название";
StringGrid2 -> Cells[2][0] = "Цена, руб";
StringGrid2 -> Cells[3][0] = "Количество";
StringGrid2 -> Cells[4][0] = "Гарантия, лет";
StringGrid2 -> Cells[5][0] = "Страна";
for(int i = 1; i < 21; i++)
{
        StringGrid1 -> Cells[0][i] = StrToInt(i);
}
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
Variant var_Excel, var_Sheet;
int Row_Counter = 0, Column_Counter = 0, Max_Column = 5, Max_Row = 7;
WideString p;
p = Edit1 -> Text;
var_Excel = CreateOleObject("Excel.Application");
var_Excel.OlePropertyGet("Application").OlePropertyGet("Workbooks").OleProcedure("Open", p);
var_Excel.OlePropertySet("Visible", false);
var_Sheet = var_Excel.OlePropertyGet("ActiveSheet");
 
for (Row_Counter; Row_Counter <= Max_Row; Row_Counter++)
{
        for (Column_Counter; Column_Counter <= Max_Column ; Column_Counter++)
        {
                StringGrid1 -> Cells[Column_Counter + 1][Row_Counter + 1] =
                var_Sheet.OlePropertyGet("Cells").OlePropertyGet("Item", Row_Counter + 1, Column_Counter + 1);
        }
        Column_Counter = 0;
}
 
var_Excel.OlePropertyGet("Application").OleProcedure("Quit");
var_Sheet = Unassigned;
var_Excel = Unassigned;
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button2Click(TObject *Sender)
{AnsiString a, e;
int b, c, d;
int n, k;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        a = StringGrid1 -> Cells[1][i];
        b = StrToInt(StringGrid1 -> Cells[2][i]);
        c = StrToInt(StringGrid1 -> Cells[3][i]);
        d = StrToInt(StringGrid1 -> Cells[4][i]);
        e = StringGrid1 -> Cells[5][i];
        char * astr = a.c_str();
        s[i].init(astr, b, c, d, e);
}
k = StrToInt(Edit2 -> Text);
for(int i = 1;i < n; i++)
{
        if(s[i] == k)
        {
                s[i].print(StringGrid2, 1);
        }
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
int b, c, d;
AnsiString a, e;
int i;
i = StrToInt(Edit8 -> Text);
a = Edit3 -> Text;
b = StrToInt(Edit4 -> Text);
c = StrToInt(Edit5 -> Text);
d = StrToInt(Edit6 -> Text);
e = Edit7 -> Text;
char * astr = a.c_str();
f[i].init(astr, b, c, d, e);
f[i].print(StringGrid1, i);
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button5Click(TObject *Sender)
{
if (!OpenDialog1 -> Execute()) return;
AnsiString  list;
 
list = OpenDialog1 -> FileName;
Edit1 -> Text = list;
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button6Click(TObject *Sender)
{
WideString str;
TStringList *sl = new TStringList;
for(int i = 1 ; i < StringGrid1 -> RowCount; ++i)
{
        for(int j = 1; j < StringGrid1 -> ColCount; ++j)
        str += StringGrid1 -> Cells[j][i] + "\t";
        sl -> Add(Trim(str));
        str = "\n\r" ;
}
 
if (SaveDialog1 -> Execute())
sl -> SaveToFile(SaveDialog1 -> FileName);
delete sl;
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button7Click(TObject *Sender)
{
Close();
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button8Click(TObject *Sender)
{
int n;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        s1[i].operator = (s[i]);
        s1[i].print(StringGrid2, i);
}
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button9Click(TObject *Sender)
{
for(int i = 0; i < StringGrid2 -> RowCount; i++)
StringGrid2 -> Rows[i] -> Clear();
 
StringGrid2 -> Cells[1][0] = "Название";
StringGrid2 -> Cells[2][0] = "Цена, руб";
StringGrid2 -> Cells[3][0] = "Количество";
StringGrid2 -> Cells[4][0] = "Гарантия, лет";
StringGrid2 -> Cells[5][0] = "Страна";
 
for(int i = 1; i < 21; i++)
{
        StringGrid2 -> Cells[0][i] = StrToInt(i);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
for(int i = 0; i < StringGrid1 -> RowCount; i++)
StringGrid1 -> Rows[i] -> Clear();
 
StringGrid1 -> Cells[1][0] = "Название";
StringGrid1 -> Cells[2][0] = "Цена, руб";
StringGrid1 -> Cells[3][0] = "Количество";
StringGrid1 -> Cells[4][0] = "Гарантия, лет";
StringGrid1 -> Cells[5][0] = "Страна";
 
for(int i = 1; i < 21; i++)
{
        StringGrid1 -> Cells[0][i] = StrToInt(i);
}
}
//---------------------------------------------------------------------------
0
162 / 162 / 42
Регистрация: 29.05.2010
Сообщений: 435
17.01.2014, 17:11
C++
1
friend bool operator == (const texnika<T> &t, int z);
Или даже так, не помню точно
C++
1
friend bool operator ==<T> (const texnika<T> &t, int z);
0
:)
Эксперт С++
4773 / 3267 / 497
Регистрация: 19.02.2013
Сообщений: 9,046
17.01.2014, 17:20
Цитата Сообщение от demigod324 Посмотреть сообщение
Unresolved external 'operator ==(const texnika<int>&, int)'
Какой смысл в сравнении объекта texnika<int> с интом?
Цитата Сообщение от demigod324 Посмотреть сообщение
s1[i].operator = (s[i]);
Однако...

Не по теме:

Наличие в коде __fastcall повышает вероятность говнокода до 99.999%.

0
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106
17.01.2014, 17:25  [ТС]
Цитата Сообщение от AnDrew_LP Посмотреть сообщение
C++
1
friend bool operator == (const texnika<T> &t, int z);
Или даже так, не помню точно
C++
1
friend bool operator ==<T> (const texnika<T> &t, int z);
Не выходит(
Может это потому, что я указал int в
C++
1
texnika<int> s[30], f[30], s1[30];
а надо что-то другое...
0
162 / 162 / 42
Регистрация: 29.05.2010
Сообщений: 435
17.01.2014, 17:27
Зачем Вам вообще шаблон? Что должна делать программа?
0
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106
17.01.2014, 17:31  [ТС]
Цитата Сообщение от AnDrew_LP Посмотреть сообщение
Зачем Вам вообще шаблон? Что должна делать программа?
Я делаю лабораторную работу, сначала мы сделали просто class, а затем его улучшали, в данной лабораторной работе надо сделать шаблон.

Цель работы: изучить способы определения шаблонов, принцип и механизм создания шаблонных классов и шаблонов функций, получить практические навыки работы с шаблонными классами.
0
:)
Эксперт С++
4773 / 3267 / 497
Регистрация: 19.02.2013
Сообщений: 9,046
17.01.2014, 17:39
Цитата Сообщение от demigod324 Посмотреть сообщение
сначала мы сделали просто class, а затем его улучшали
смешно.
Цитата Сообщение от demigod324 Посмотреть сообщение
в данной лабораторной работе надо сделать шаблон.
Чтобы был смысл в шаблоне, в классе было бы неплохо добавить поле, зависимое от параметра шаблона.
0
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106
17.01.2014, 17:50  [ТС]
Цитата Сообщение от Tulosba Посмотреть сообщение
смешно.

Чтобы был смысл в шаблоне, в классе было бы неплохо добавить поле, зависимое от параметра шаблона.
А можно какой - нибудь наглядный пример?
0
:)
Эксперт С++
4773 / 3267 / 497
Регистрация: 19.02.2013
Сообщений: 9,046
17.01.2014, 17:53
Цитата Сообщение от demigod324 Посмотреть сообщение
А можно какой - нибудь наглядный пример?
std::vector<T>. Параметр шаблона задает тип значений хранимых в контейнере.
В коде:
C++
1
2
3
4
5
6
template <class T>
class SomeClass
{
...
   T t; // переменная-член типа, зависимого от параметра шаблона
}
1
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106
18.01.2014, 09:46  [ТС]
Цитата Сообщение от Tulosba Посмотреть сообщение
std::vector<T>. Параметр шаблона задает тип значений хранимых в контейнере.
В коде:
C++
1
2
3
4
5
6
template <class T>
class SomeClass
{
...
   T t; // переменная-член типа, зависимого от параметра шаблона
}
Ну ладно, я возможно попробую сделать что-то наподобие, но ошибка то никуда не пропала! Помогите пожалуйста исправить ее.

Добавлено через 15 часов 24 минуты
Ребят, никто не знает как решить данную проблему?
0
:)
Эксперт С++
4773 / 3267 / 497
Регистрация: 19.02.2013
Сообщений: 9,046
18.01.2014, 13:54
Цитата Сообщение от demigod324 Посмотреть сообщение
Ребят, никто не знает как решить данную проблему?
Чтобы Вам помогли быстрее, напишите минимально достаточный код, в котором проявляется проблема.
0
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106
19.01.2014, 11:41  [ТС]
Цитата Сообщение от Tulosba Посмотреть сообщение
Чтобы Вам помогли быстрее, напишите минимально достаточный код, в котором проявляется проблема.
Вот минимальный код, при котором возникает проблема

[Linker Error] Unresolved external 'operator ==(const texnika<int>&, int)' referenced from C:\PROGRAM FILES\BORLAND\CBUILDER6\PROJECTS\UNIT1.O BJ

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
//---------------------------------------------------------------------------
 
#include <vcl.h>
#include <comobj.hpp>
#include <Grids.hpp>
#include <stdlib.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
 
template <class T>
class texnika
{
char *name;
int zena;
AnsiString strana;
 
public: void init(char *n, int z, AnsiString s);
int sravn(int z);
void print(TStringGrid *Stringgrid1, int n);
void prisv(const texnika &t);
texnika();
texnika(char *n, int z, AnsiString s);
texnika(const texnika &t);
~texnika() {delete[] name;};
texnika &operator = (const texnika &t);
friend bool operator == (const texnika &t, int z);
};
 
texnika<int> s[30], f[30], s1[30];
 
TForm1 *Form1;
//---------------------------------------------------------------------------
template <class T>
void texnika<T>::prisv(const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
strana = t.strana;}
 
template <class T>
void texnika<T>::init(char *n, int z, AnsiString s)
{
name = new char [strlen(n) + 1];
strcpy(name, n);
zena = z;
strana = s;}
 
template <class T>
int texnika<T>::sravn(int z)
{
if(zena == z)
return 0;
else return 1;
}
 
template <class T>
void texnika<T>::print(TStringGrid *StringGrid1, int n)
{
StringGrid1 -> Cells[1][n] = name;
StringGrid1 -> Cells[2][n] = zena;
StringGrid1 -> Cells[5][n] = strana;
}
 
template <class T>
texnika<T>::texnika()
{
name = "Название";
strcpy(name, "Название");
zena = 0;
strana = "Китай";
}
 
template <class T>
texnika<T>::texnika(char *n, int z, AnsiString s)
{
name = new char [strlen(n) + 1];
strcpy(name, n);
zena = z;
strana = s;
}
 
template <class T>
texnika<T>::texnika(const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
strana = t.strana;
}
 
template <class T>
texnika<T> &texnika<T>::operator = (const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
strana = t.strana;
return *this;
}
 
template <class T>
bool operator == (const texnika<T> &t, int z)
{
return t.zena == z;
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button2Click(TObject *Sender)
{
AnsiString a, e;
int b;
int n, k;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        a = StringGrid1 -> Cells[1][i];
        b = StrToInt(StringGrid1 -> Cells[2][i]);
        e = StringGrid1 -> Cells[5][i];
        char * astr = a.c_str();
        s[i].init(astr, b, e);
}
k = StrToInt(Edit2 -> Text);
for(int i = 1;i < n; i++)
{
        if(s[i] == k)
        {
                s[i].print(StringGrid2, 1);
        }
}
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button3Click(TObject *Sender)
{
int b;
AnsiString a, e;
int i;
i = StrToInt(Edit8 -> Text);
a = Edit3 -> Text;
b = StrToInt(Edit6 -> Text);
e = Edit7 -> Text;
char * astr = a.c_str();
f[i].init(astr, b, e);
f[i].print(StringGrid1, i);
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button8Click(TObject *Sender)
{
int n;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        s1[i].operator = (s[i]);
        s1[i].print(StringGrid2, i);
}
}
//---------------------------------------------------------------------------
Добавлено через 16 часов 45 минут
Сделал код еще меньше, ошибка присутствует до сих пор

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
//---------------------------------------------------------------------------
 
#include <vcl.h>
#include <comobj.hpp>
#include <Grids.hpp>
#include <stdlib.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
 
template <class T>
class texnika
{
char *name;
int zena;
AnsiString strana;
 
public: void init(char *n, int z, AnsiString s);
int sravn(int z);
void print(TStringGrid *Stringgrid1, int n);
void prisv(const texnika &t);
friend bool operator == (const texnika &t, int z);
};
 
texnika<int> s[30], f[30], s1[30];
 
TForm1 *Form1;
//---------------------------------------------------------------------------
template <class T>
void texnika<T>::prisv(const texnika<T> &t)
{
name = new char [strlen(t.name) + 1];
strcpy(name, t.name);
zena = t.zena;
strana = t.strana;}
 
template <class T>
void texnika<T>::init(char *n, int z, AnsiString s)
{
name = new char [strlen(n) + 1];
strcpy(name, n);
zena = z;
strana = s;}
 
template <class T>
int texnika<T>::sravn(int z)
{
if(zena == z)
return 0;
else return 1;
}
 
template <class T>
void texnika<T>::print(TStringGrid *StringGrid1, int n)
{
StringGrid1 -> Cells[1][n] = name;
StringGrid1 -> Cells[2][n] = zena;
StringGrid1 -> Cells[5][n] = strana;
}
 
template <class T>
bool operator == (const texnika<T> &t, int z)
{
return t.zena == z;
}
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button2Click(TObject *Sender)
{
AnsiString a, e;
int b;
int n, k;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        a = StringGrid1 -> Cells[1][i];
        b = StrToInt(StringGrid1 -> Cells[2][i]);
        e = StringGrid1 -> Cells[5][i];
        char * astr = a.c_str();
        s[i].init(astr, b, e);
}
k = StrToInt(Edit2 -> Text);
for(int i = 1;i < n; i++)
{
        if(s[i] == k)
        {
                s[i].print(StringGrid2, 1);
        }
}
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button3Click(TObject *Sender)
{
int b;
AnsiString a, e;
int i;
i = StrToInt(Edit8 -> Text);
a = Edit3 -> Text;
b = StrToInt(Edit6 -> Text);
e = Edit7 -> Text;
char * astr = a.c_str();
f[i].init(astr, b, e);
f[i].print(StringGrid1, i);
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button8Click(TObject *Sender)
{
int n;
n = StrToInt(Edit10 -> Text);
for(int i = 1; i < n; i++)
{
        s1[i].operator = (s[i]);
        s1[i].print(StringGrid2, i);
}
}
//---------------------------------------------------------------------------
0
Почетный модератор
Эксперт С++
 Аватар для SatanaXIII
5851 / 2862 / 392
Регистрация: 01.11.2011
Сообщений: 6,906
20.01.2014, 11:48
А если заменить вот это на вот это:
C++
1
2
//friend bool operator == (const texnika &t, int z);
bool operator == (int z);
И соответственно вот это на вот это:
C++
1
2
3
4
5
6
7
8
9
10
template <class T>
bool texnika<T>::operator == (int z)
{
return this->zena == z;
}
/*template <class T>
bool operator == (const texnika<T> &t, int z)
{
return t.zena == z;
}*/
0
98 / 81 / 14
Регистрация: 26.07.2013
Сообщений: 594
20.01.2014, 15:42
- demigod324, сделал следующее:
a) Выделил Ваш класс texnika в отдельный модуль (TEXNIKA). Так все лучше структурировано, да и
правильнее.
b) Изменил Вашу перегрузку оператора сравнения на ту, какую указал SatanaXIII.
c) Явно инстанцировал Ваш класс texnika на тип (int). Смотрите в модуле TEXNIKA, в самом низу файла
TEXNIKA.cpp. Без этого компилятор не найдет реализаций методов Вашего класса texnika. Он все время
будет давать сообщения "Unresolved ...".
- Если Вы будете использовать Ваш шаблонный класс texnika с каким либо другим типом (а не int), то
нужно будет точно так-же явно инстанцировать класс и на другой тип тоже.
Вложения
Тип файла: rar Vers_0.rar (119.6 Кб, 3 просмотров)
1
4 / 2 / 2
Регистрация: 17.03.2013
Сообщений: 106
20.01.2014, 20:54  [ТС]
Цитата Сообщение от Staut Посмотреть сообщение
- demigod324, сделал следующее:
a) Выделил Ваш класс texnika в отдельный модуль (TEXNIKA). Так все лучше структурировано, да и
правильнее.
b) Изменил Вашу перегрузку оператора сравнения на ту, какую указал SatanaXIII.
c) Явно инстанцировал Ваш класс texnika на тип (int). Смотрите в модуле TEXNIKA, в самом низу файла
TEXNIKA.cpp. Без этого компилятор не найдет реализаций методов Вашего класса texnika. Он все время
будет давать сообщения "Unresolved ...".
- Если Вы будете использовать Ваш шаблонный класс texnika с каким либо другим типом (а не int), то
нужно будет точно так-же явно инстанцировать класс и на другой тип тоже.
Спасибо огромное, хоть и препод вроде втолковал мне как сделать правильно), но все равно спасибо)
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
20.01.2014, 20:54
Помогаю со студенческими работами здесь

Visual Studio выдаёт ошибку при вынесении объявления функции с template в .h файл. Без template всё работает
Проект содержит три файла: Source.cpp, arrTreat.h, arrTreat.cpp. Source.cpp: #include &lt;iostream&gt; using std::cout; using...

Ошибка с django.Template.Template
Из учебника djbook: http://djbook.ru/ch04s02.html В самом начале представлен пример использования шаблонов: &gt;&gt;&gt; from django...

Ошибка "Too many parameters were provided in this RPC request" при вызове хранимой процедуры
При отправке параметров на хранимую процедуру выдает ошибку. The incoming tabular data stream (TDS) remote procedure call (RPC)...

Ошибка при открытии формы "the wrong parameters were passed to the converter. To convert files, open them from the file menu."
Здравствуйте! Подскажите пожалуйста. У меня есть форма, на ней грид. Все работало нормально. Перед перезагрузкой на автомате сохранил...

Ошибка при установке Yii2-user with Yii2 advanced template
https://github.com/dektrium/yii2-user/blob/master/docs/usage-with-advanced-template.md Ошибка An Error occurred while...


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

Или воспользуйтесь поиском по форуму:
17
Ответ Создать тему
Новые блоги и статьи
Оттенки серого
Argus19 18.03.2026
Оттенки серого Нашёл в интернете 3 прекрасных модуля: Модуль класса открытия диалога открытия/ сохранения файла на Win32 API; Модуль класса быстрого перекодирования цветного изображения в оттенки. . .
SDL3 для Desktop (MinGW): Рисуем цветные прямоугольники с помощью рисовальщика SDL3 на Си и C++
8Observer8 17.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-rectangles-sdl3-c. zip finish-rectangles-sdl3-cpp. zip
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая ссылка» (hard link),. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
делаю науч статью по влиянию грибов на сукцессию
anaschu 13.03.2026
прикрепляю статью
SDL3 для Desktop (MinGW): Создаём пустое окно с нуля для 2D-графики на SDL3, Си и C++
8Observer8 10.03.2026
Содержание блога Финальные проекты на Си и на C++: hello-sdl3-c. zip hello-sdl3-cpp. zip Результат:
Установка CMake и MinGW 13.1 для сборки С и C++ приложений из консоли и из Qt Creator в EXE
8Observer8 10.03.2026
Содержание блога MinGW - это коллекция инструментов для сборки приложений в EXE. CMake - это система сборки приложений. Здесь описаны базовые шаги для старта программирования с помощью CMake и. . .
Как дизайн сайта влияет на конверсию: 7 решений, которые реально повышают заявки
Neotwalker 08.03.2026
Многие до сих пор воспринимают дизайн сайта как “красивую оболочку”. На практике всё иначе: дизайн напрямую влияет на то, оставит человек заявку или уйдёт через несколько секунд. Даже если у вас. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru