Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.63/8: Рейтинг темы: голосов - 8, средняя оценка - 4.63
9 / 9 / 0
Регистрация: 19.04.2012
Сообщений: 114
1

Не получается вынести класс в отдельный файл

21.06.2013, 21:24. Показов 1555. Ответов 3
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый вечер. Не получается вынести код в отдельный файл. есть заголовочный файл, и есть файл с методами. При компиляции выдает ошибку "error C2011: cTGA: переопределение типа "class"". Опыта работы с C++ мало, поэтому не могу разобраться в чем проблема. Помогите пожалуйста. Вот исходный код:
cTGA.h:
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
#pragma once 
#include "stdafx.h"
class cTGA
{
    public:
        cTGA()
        {   //конструктор
            uTGAcompare[0] = 0;
            uTGAcompare[1] = 0;
            uTGAcompare[2] = 2;
            uTGAcompare[3] = 0;
            uTGAcompare[4] = 0;
            uTGAcompare[5] = 0;
            uTGAcompare[6] = 0;
            uTGAcompare[7] = 0;
            uTGAcompare[8] = 0;
            uTGAcompare[9] = 0;
            uTGAcompare[10] = 0;
            uTGAcompare[11] = 0;
 
            cTGAcompare[0] = 0;
            cTGAcompare[1] = 0;
            cTGAcompare[2] = 10;
            cTGAcompare[3] = 0;
            cTGAcompare[4] = 0;
            cTGAcompare[5] = 0;
            cTGAcompare[6] = 0;
            cTGAcompare[7] = 0;
            cTGAcompare[8] = 0;
            cTGAcompare[9] = 0;
            cTGAcompare[10] = 0;
            cTGAcompare[11] = 0;
        };
        ~cTGA();
        struct Texture
        {
            GLubyte * imageData;                                    // Image Data (Up To 32 Bits)
            GLuint  bpp;                                            // Image Color Depth In Bits Per Pixel
            GLuint  width;                                          // Image Width
            GLuint  height;                                         // Image Height
            GLuint  texID;                                          // Texture ID Used To Select A Texture
            GLuint  type;                                           // Image Type (GL_RGB, GL_RGBA)
            bool load;// текстура загружена или нет
        };
 
        struct TGAHeader{
            GLubyte Header[12];                                 // TGA File Header
        };
 
        struct TGA
        {
            GLubyte     header[6];                              // First 6 Useful Bytes From The Header
            GLuint      bytesPerPixel;                          // Holds Number Of Bytes Per Pixel Used In The TGA File
            GLuint      imageSize;                              // Used To Store The Image Size When Setting Aside Ram
            GLuint      temp;                                   // Temporary Variable
            GLuint      type;
            GLuint      Height;                                 //Height of Image
            GLuint      Width;                                  //Width ofImage
            GLuint      Bpp;                                    // Bits Per Pixel
        };
 
        TGAHeader tgaheader;                                    // TGA header
        TGA tga;                                                // TGA image data
        GLubyte uTGAcompare[12];    // Uncompressed TGA Header
        GLubyte cTGAcompare[12];    // Compressed TGA Header
        Texture texture[100];// здесь хранятся текстуры
        bool LoadUncompressedTGA(Texture * texture, char * filename, FILE * fTGA);
        bool LoadCompressedTGA(Texture * texture, char * filename, FILE * fTGA);
        bool LoadTGA(Texture * texture, char * filename);
        GLvoid LoadGLTextures();
 
};
И cTGA.cpp:
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#pragma once
#include "stdafx.h"
class cTGA
{
public:
    //загрузка несжатого изображения
    bool LoadUncompressedTGA(Texture * texture, char * filename, FILE * fTGA)
    {
        // TGA Loading code nehe.gamedev.net)
        if(fread(tga.header, sizeof(tga.header), 1, fTGA) == 0){                    // Read TGA header
            MessageBox(NULL, L"Could not read info header", L"ERROR", MB_OK);       // Display error
            if(fTGA != NULL){                                                   // if file is still open
                fclose(fTGA);                                                   // Close it
            }
            return false;                                                       // Return failular
        }
 
        texture->width  = tga.header[1] * 256 + tga.header[0];                  // Determine The TGA Width  (highbyte*256+lowbyte)
        texture->height = tga.header[3] * 256 + tga.header[2];                  // Determine The TGA Height (highbyte*256+lowbyte)
        texture->bpp    = tga.header[4];                                        // Determine the bits per pixel
        tga.Width       = texture->width;                                       // Copy width into local structure
        tga.Height      = texture->height;                                      // Copy height into local structure
        tga.Bpp         = texture->bpp;                                         // Copy BPP into local structure
 
        if((texture->width <= 0) || (texture->height <= 0) || ((texture->bpp != 24) && (texture->bpp !=32))){   // Make sure all information is valid
            MessageBox(NULL, L"Invalid texture information", L"ERROR", MB_OK);  // Display Error
            if(fTGA != NULL){                                                   // Check if file is still open
                fclose(fTGA);                                                   // If so, close it
            }
            return false;                                                       // Return failed
        }
 
        if(texture->bpp == 24)                                                  // If the BPP of the image is 24...
            texture->type   = GL_RGB;                                           // Set Image type to GL_RGB
        else                                                                    // Else if its 32 BPP
            texture->type   = GL_RGBA;                                          // Set image type to GL_RGBA
 
        tga.bytesPerPixel   = (tga.Bpp / 8);                                    // Compute the number of BYTES per pixel
        tga.imageSize       = (tga.bytesPerPixel * tga.Width * tga.Height);     // Compute the total amout ofmemory needed to store data
        texture->imageData  = (GLubyte *)malloc(tga.imageSize);                 // Allocate that much memory
 
        if(texture->imageData == NULL){                                         // If no space was allocated
            MessageBox(NULL, L"Could not allocate memory for image", L"ERROR", MB_OK);  // Display Error
            fclose(fTGA);                                                       // Close the file
            return false;                                                       // Return failed
        }
 
        if(fread(texture->imageData, 1, tga.imageSize, fTGA) != tga.imageSize){ // Attempt to read image data
            MessageBox(NULL, L"Could not read image data", L"ERROR", MB_OK);        // Display Error
            if(texture->imageData != NULL){                                     // If imagedata has data in it
                free(texture->imageData);                                       // Delete data from memory
            }
            fclose(fTGA);                                                       // Close file
            return false;                                                       // Return failed
        }
 
        // Byte Swapping Optimized By Steve Thomas
        for(GLuint cswap = 0; cswap < (int)tga.imageSize; cswap += tga.bytesPerPixel){
            texture->imageData[cswap] ^= texture->imageData[cswap+2] ^=
                texture->imageData[cswap] ^= texture->imageData[cswap+2];
        }
 
        fclose(fTGA);                                                           // Close file
        return true;                                                            // Return success
    }
    //загрузка сжатого изображения
    bool LoadCompressedTGA(Texture * texture, char * filename, FILE * fTGA)
    {
        if(fread(tga.header, sizeof(tga.header), 1, fTGA) == 0){                    // Attempt to read header
            MessageBox(NULL, L"Could not read info header", L"ERROR", MB_OK);       // Display Error
            if(fTGA != NULL) fclose(fTGA);                                          // If file is open, close it
            return false;                                                       // Return failed
        }
 
        texture->width  = tga.header[1] * 256 + tga.header[0];                  // Determine The TGA Width  (highbyte*256+lowbyte)
        texture->height = tga.header[3] * 256 + tga.header[2];                  // Determine The TGA Height (highbyte*256+lowbyte)
        texture->bpp    = tga.header[4];                                        // Determine Bits Per Pixel
        tga.Width       = texture->width;                                       // Copy width to local structure
        tga.Height      = texture->height;                                      // Copy width to local structure
        tga.Bpp         = texture->bpp;                                         // Copy width to local structure
 
        if((texture->width <= 0) || (texture->height <= 0) || ((texture->bpp != 24) && (texture->bpp !=32))){   //Make sure all texture info is ok
            MessageBox(NULL, L"Invalid texture information", L"ERROR", MB_OK);  // If it isnt...Display error
            if(fTGA != NULL) fclose(fTGA);                                      // Check if file is open
            return false;                                                       // Return failed
        }
 
        if(texture->bpp == 24)                                                  // If the BPP of the image is 24...
            texture->type   = GL_RGB;                                           // Set Image type to GL_RGB
        else                                                                    // Else if its 32 BPP
            texture->type   = GL_RGBA;                                          // Set image type to GL_RGBA
 
        tga.bytesPerPixel   = (tga.Bpp / 8);                                    // Compute BYTES per pixel
        tga.imageSize       = (tga.bytesPerPixel * tga.Width * tga.Height);     // Compute amout of memory needed to store image
        texture->imageData  = (GLubyte *)malloc(tga.imageSize);                 // Allocate that much memory
 
        if(texture->imageData == NULL){                                         // If it wasnt allocated correctly..
            MessageBox(NULL, L"Could not allocate memory for image", L"ERROR", MB_OK);  // Display Error
            fclose(fTGA);                                                       // Close file
            return false;                                                       // Return failed
        }
 
        GLuint pixelcount   = tga.Height * tga.Width;                           // Nuber of pixels in the image
        GLuint currentpixel = 0;                                                // Current pixel being read
        GLuint currentbyte  = 0;                                                // Current byte
        GLubyte * colorbuffer = (GLubyte *)malloc(tga.bytesPerPixel);           // Storage for 1 pixel
 
        do{
            GLubyte chunkheader = 0;                                            // Storage for "chunk" header
            if(fread(&chunkheader, sizeof(GLubyte), 1, fTGA) == 0){             // Read in the 1 byte header
                MessageBox(NULL, L"Could not read RLE header", L"ERROR", MB_OK);    // Display Error
                if(fTGA != NULL){                                               // If file is open
                    fclose(fTGA);                                               // Close file
                }
                if(texture->imageData != NULL)                                  // If there is stored image data
                {
                    free(texture->imageData);                                   // Delete image data
                }
                return false;                                                   // Return failed
            }
 
            if(chunkheader < 128)                                               // If the ehader is < 128, it means the that is the number of RAW color packets minus 1
            {                                                                   // that follow the header
                chunkheader++;                                                  // add 1 to get number of following color values
                for(short counter = 0; counter < chunkheader; counter++)        // Read RAW color values
                {
                    if(fread(colorbuffer, 1, tga.bytesPerPixel, fTGA) != tga.bytesPerPixel) // Try to read 1 pixel
                    {
                        MessageBox(NULL, L"Could not read image data", L"ERROR", MB_OK);        // IF we cant, display an error
 
                        if(fTGA != NULL)                                                    // See if file is open
                        {
                            fclose(fTGA);                                                   // If so, close file
                        }
 
                        if(colorbuffer != NULL)                                             // See if colorbuffer has data in it
                        {
                            free(colorbuffer);                                              // If so, delete it
                        }
 
                        if(texture->imageData != NULL)                                      // See if there is stored Image data
                        {
                            free(texture->imageData);                                       // If so, delete it too
                        }
 
                        return false;                                                       // Return failed
                    }
                    // write to memory
                    texture->imageData[currentbyte      ] = colorbuffer[2];                 // Flip R and B vcolor values around in the process
                    texture->imageData[currentbyte + 1  ] = colorbuffer[1];
                    texture->imageData[currentbyte + 2  ] = colorbuffer[0];
 
                    if(tga.bytesPerPixel == 4)                                              // if its a 32 bpp image
                    {
                        texture->imageData[currentbyte + 3] = colorbuffer[3];               // copy the 4th byte
                    }
 
                    currentbyte += tga.bytesPerPixel;                                       // Increase thecurrent byte by the number of bytes per pixel
                    currentpixel++;                                                         // Increase current pixel by 1
 
                    if(currentpixel > pixelcount)                                           // Make sure we havent read too many pixels
                    {
                        MessageBox(NULL, L"Too many pixels read", L"ERROR", NULL);          // if there is too many... Display an error!
 
                        if(fTGA != NULL)                                                    // If there is a file open
                        {
                            fclose(fTGA);                                                   // Close file
                        }
 
                        if(colorbuffer != NULL)                                             // If there is data in colorbuffer
                        {
                            free(colorbuffer);                                              // Delete it
                        }
 
                        if(texture->imageData != NULL)                                      // If there is Image data
                        {
                            free(texture->imageData);                                       // delete it
                        }
 
                        return false;                                                       // Return failed
                    }
                }
            }
            else                                                                            // chunkheader > 128 RLE data, next color reapeated chunkheader - 127 times
            {
                chunkheader -= 127;                                                         // Subteact 127 to get rid of the ID bit
                if(fread(colorbuffer, 1, tga.bytesPerPixel, fTGA) != tga.bytesPerPixel)     // Attempt to read following color values
                {
                    MessageBox(NULL, L"Could not read from file", L"ERROR", MB_OK);         // If attempt fails.. Display error (again)
 
                    if(fTGA != NULL)                                                        // If thereis a file open
                    {
                        fclose(fTGA);                                                       // Close it
                    }
 
                    if(colorbuffer != NULL)                                                 // If there is data in the colorbuffer
                    {
                        free(colorbuffer);                                                  // delete it
                    }
 
                    if(texture->imageData != NULL)                                          // If thereis image data
                    {
                        free(texture->imageData);                                           // delete it
                    }
 
                    return false;                                                           // return failed
                }
 
                for(short counter = 0; counter < chunkheader; counter++)                    // copy the color into the image data as many times as dictated
                {                                                                           // by the header
                    texture->imageData[currentbyte      ] = colorbuffer[2];                 // switch R and B bytes areound while copying
                    texture->imageData[currentbyte + 1  ] = colorbuffer[1];
                    texture->imageData[currentbyte + 2  ] = colorbuffer[0];
 
                    if(tga.bytesPerPixel == 4)                                              // If TGA images is 32 bpp
                    {
                        texture->imageData[currentbyte + 3] = colorbuffer[3];               // Copy 4th byte
                    }
 
                    currentbyte += tga.bytesPerPixel;                                       // Increase current byte by the number of bytes per pixel
                    currentpixel++;                                                         // Increase pixel count by 1
 
                    if(currentpixel > pixelcount)                                           // Make sure we havent written too many pixels
                    {
                        MessageBox(NULL, L"Too many pixels read", L"ERROR", NULL);          // if there is too many... Display an error!
 
                        if(fTGA != NULL)                                                    // If there is a file open
                        {
                            fclose(fTGA);                                                   // Close file
                        }
 
                        if(colorbuffer != NULL)                                             // If there is data in colorbuffer
                        {
                            free(colorbuffer);                                              // Delete it
                        }
 
                        if(texture->imageData != NULL)                                      // If there is Image data
                        {
                            free(texture->imageData);                                       // delete it
                        }
 
                        return false;                                                       // Return failed
                    }
                }
            }
        }
 
        while(currentpixel < pixelcount);                                                   // Loop while there are still pixels left
        fclose(fTGA);                                                                       // Close the file
        return true;                                                                       // return success
    }
    //загрузка файла
    bool LoadTGA(Texture * texture, char * filename)
    {
        FILE * fTGA;                                                // File pointer to texture file
        fTGA = fopen(filename, "rb");                               // Open file for reading
        if(fTGA == NULL){                                           // If it didn't open....
            //MessageBox(NULL, L"Could not open texture file", L"ERROR", MB_OK);    // Display an error message
            return false;                                                       // Exit function
        }
 
        if(fread(&tgaheader, sizeof(TGAHeader), 1, fTGA) == 0){                 // Attempt to read 12 byte header from file
            MessageBox(NULL, L"Could not read file header", L"ERROR", MB_OK);       // If it fails, display an error message
            if(fTGA != NULL) fclose(fTGA);                                                  // Check to seeiffile is still open
            return false;                                                       // Exit function
        }
 
        if(memcmp(uTGAcompare, &tgaheader, sizeof(tgaheader)) == 0){                // See if header matches the predefined header of
            // an Uncompressed TGA image
            LoadUncompressedTGA(texture, filename, fTGA);                       // If so, jump to Uncompressed TGA loading code
        }
        else if(memcmp(cTGAcompare, &tgaheader, sizeof(tgaheader)) == 0)        // See if header matches the predefined header of
        {                                                                       // an RLE compressed TGA image
            LoadCompressedTGA(texture, filename, fTGA);                         // If so, jump to Compressed TGA loading code
        }
        else                                                                    // If header matches neither type
        {
            MessageBox(NULL, L"TGA file be type 2 or type 10 ", L"Invalid Image", MB_OK);   // Display an error
            fclose(fTGA);
            return false;                                                               // Exit function
        }
        return true;                                                            // All went well, continue on
    }
    // Загрузка картинки и конвертирование в текстуру
    GLvoid LoadGLTextures()
    {
 
        //загрузка непрозрачных текстур
        texture[0].load = LoadTGA(&texture[0], "C:\\image.tga");// какая-то текстура
        // здесь же можно добавить еще текстур, например
        //texture[1].load = LoadTGA(&texture[1], "test2.tga");// вторая текстура
 
 
        if(texture[0].load) glGenTextures(1, &texture[0].texID);
        // if(texture[1].load) glGenTextures(1, &texture[1].texID);// это для второй текстуры
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);// выравнивание в массиве данных идет по байту
 
        //создание текстуры 1
        glBindTexture(GL_TEXTURE_2D, texture[0].texID);
        if(texture[0].load)
        {
            glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
            glTexImage2D(GL_TEXTURE_2D, 0, texture[0].bpp / 8, texture[0].width, texture[0].height, 0,
                texture[0].type, GL_UNSIGNED_BYTE, texture[0].imageData);
            if (texture[0].texID)
            {           // Если текстура существует
                if (texture[0].imageData)
                {    // Если изображение текстуры существует
                    free(texture[0].imageData); // Освобождение памяти изображения текстуры
                }
            }           
        }
    }
};
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
21.06.2013, 21:24
Ответы с готовыми решениями:

как вынести класс в отдельный файл?
сделал простенький класс class cool { public: cool(); int ga(); int gb(); void...

Можно ли вынести класс в отдельный файл
Можно ли вынести класс в отдельный файл? А потом его подключить, а то у меня получается жуткая...

Nebeans, как вынести класс в отдельный файл?
Написал я два публичных класса в одном файле, компилятор, естественно, заругался. Можно, конечно,...

Как вынести класс в отдельный файл с namespace?
Добрый вечер, есть проблема, не выносится класс в отдельный файл, пишет что переопределение типа...

3
Неэпический
17869 / 10634 / 2054
Регистрация: 27.09.2012
Сообщений: 26,736
Записей в блоге: 1
21.06.2013, 22:32 2
Цитата Сообщение от Демик Посмотреть сообщение
cTGA.h:
Цитата Сообщение от Демик Посмотреть сообщение
cTGA.cpp:
ну так в каждом же по классу cTGA
1
419 / 418 / 72
Регистрация: 27.05.2012
Сообщений: 1,168
21.06.2013, 22:35 3
Цитата Сообщение от Демик Посмотреть сообщение
class cTGA
{
public:
* * //загрузка несжатого изображения
* * bool LoadUncompressedTGA(Texture * texture, char * filename, FILE * fTGA)
* * {
/*тило*/
* * * * }
надо

C++
1
2
3
4
bool cTGA::LoadUncompressedTGA(Texture * texture, char * filename, FILE * fTGA)
{
/*тило*/
}
1
9 / 9 / 0
Регистрация: 19.04.2012
Сообщений: 114
21.06.2013, 22:45  [ТС] 4
Спасибо, я таки понял!
Да, работает, спасибо
0
21.06.2013, 22:45
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
21.06.2013, 22:45
Помогаю со студенческими работами здесь

Как вынести класс в отдельный файл сочетаниями клавиш
Подскажите, в vs как вынести класс в отдельный файл сочетанием клавиш?

Вынести метод в отдельный класс
У меня есть вот такой метод, все данные типа String и два типа double public void...

Вынести методы в отдельный класс
Есть программа, которая считает комплексные числа, не понимаю как вынести например функции операций...

Вынести обработчики событий в отдельный класс
Доброго времени суток. Столкнулся с проблемой, которая уже вроде неоднократно поднималась на...


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

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru