One of the header files is as follows —
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
When I try to compile the project, I get the error
error C2011: 'AAA' : 'class' type redefinition
Nowhere else in my program have I redefined the class AAA
. How do I fix this?
meJustAndrew
5,6577 gold badges53 silver badges71 bronze badges
asked Sep 7, 2014 at 19:01
1
Change to code to something like this:
#ifndef AAA_HEADER
#define AAA_HEADER
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
#endif
If you include this header file more than once in some source file, include guards will force compiler to generate class only once so it will not give class redefinition
error.
answered Sep 7, 2014 at 19:06
AshotAshot
10.7k13 gold badges63 silver badges114 bronze badges
3
Adding
#pragma once
to the top of your AAA.h file should take care of the problem.
like this
#include "stdafx.h"
#pragma once
class AAA
{
public:
std::string strX;
std::string strY;
};
answered Jun 7, 2016 at 18:09
emptyempty
4,9923 gold badges32 silver badges57 bronze badges
1
In addition to the suggested include guards you need to move #include «stdafx.h» out of the header. Put it at the top of the cpp file.
answered Sep 7, 2014 at 20:17
ScottMcP-MVPScottMcP-MVP
10.3k2 gold badges14 silver badges15 bronze badges
I met this problem today in VS 2017. I added #pragma once
, but it didn’t work until I added a macro definition:
// does not work
#pragma once
// works with or without #pragma once
#ifndef _HEADER_AAA
#define _HEADER_AAA
//
// my code here....
//
#endif
I have no clue how to explain this, but it is a solution for me.
Yun
2,8346 gold badges8 silver badges28 bronze badges
answered Sep 15, 2021 at 5:48
- Forum
- Beginners
- Error : ‘class’ type redefinition
Error : ‘class’ type redefinition
Hello,
I have structure of my classes as follows
Object.cpp
Integer.cpp
|
|
Boolean.cpp
|
|
Main.cpp
|
|
When i compile the project i get error as
error C2011: ‘Object’ : ‘class’ type redefinition
Now, in Main.cpp file i make use of both Integer and Boolean so isn’t including this files valid?
help appreciated
amal
Yes you will get C2011: ‘Object’ : ‘class’ type redefinition
error.
This is because main.cpp line 1 — includes interger.cpp which itself includes object.cpp.
and on line 2 there is include object.cpp
So object cpp gets included twice which means that class Object is seen twice by the compiler — hence the error.
The way you are including cpp files is not the recommended way of doing things.
Class declarations are usually put into header files. The code for the class is put into the cpp file.
The header file should have a header guard to prevent multiple inclusion errors.
Example of header guard
object.h
|
|
Do something similar for the other class declaration files;
integer.h
|
|
boolean.h
|
|
Then in main.cpp you will have:
|
|
Thanks, guestgulkan …that helped…
Hello,
I am facing a tye cast problem, but logically it seems right.
Modifying Integer.cpp
|
|
Modifying Main.cpp
|
|
The error given is :-
‘type cast’ : cannot convert from ‘class Object’ to ‘class Boolean’
An Object is been returned which is just type casted to Child-class(Boolean).
What am i missing?
help appreciated
amal
Sometimes what can be casted to what sometimes confues me.
But the Object& Integer::getElementAt(int index)
returns a
reference.
So change this line Boolean b=(Boolean)i.getElementAt(0);
to read like this:
Boolean b = static_cast<Boolean&>(i.getElementAt(0));
NOTE:
Casting a derived class to a base class is not always safe.
Yes, this cast only works in very limited cases and there are trivial ways to modify Integer and/or Boolean that would cause this code to fail eventually.
Without stepping onto the design soapbox, perhaps one solution would be to write some casting constructors:
|
|
Hello,
I thought i understood the passing objects by reference well…not though….
Modifying Object.cpp
Modifying Integer.cpp
|
|
Adding Vector.cpp
|
|
Modifying Mainc.pp
|
|
Now logically, value_a and value_b should be same.
Because, i have passed Integer object by reference.
It means Integer Reference «a» and «c» should be same…but it seems they aren’t.
what have i missed?
Looked at concept of passing by references on net…the concept applied seems to be same.
help appreciated
amal
Your problem is called splicing.
In Vector, you declare an array of Objects by pointer: Object* data;
.
When you new Object[100]
, you are allocating memory for 100 Objects. Object is an empty class.
Now in addElement, you take an object passed by reference and put it into the array. The array holds only Objects, however. This means that the compiler is «splicing» your parameter into two pieces — the Object part and «the «rest» — and it is copying ONLY THE Object PART into the array.
You have essentially lost the derived portion of your object at this point. This, of course, then makes your static_cast on line 9 in Mainc.cpp invalid.
This is not going to be an easy thing to fix. However, I will make one suggestion to you (kind of related):
Use dynamic_cast<> instead of static_cast<> for polymorphic «downcasting». This will actually cause the compiler to generate code to ensure the cast is legal. Had you done this on the above code, an exception would have been thrown on line 9.
(Note: if you dynamic_cast to a pointer, NULL is returned if the cast fails. if you dynamic_cast to a reference, an exception is thrown on failure instead).
«This means that the compiler is «splicing» your parameter into two pieces — the Object part and «the «rest» — and it is copying ONLY THE Object PART into the array.» —>
This means that i have to make an array for holding references to objects.
But a bit of look here and there…got to know that creating array for holding references is not possible in c++.
so, what can be the possible solution to it?
amal
Probably pointers are your only option, but that could be a fairly significant change to your application.
Topic archived. No new replies allowed.
- HowTo
- C++ Howtos
- Class Type Redefinition in C++

In this guide, we will learn about the error class type redefinition in C++ and how to avoid this error. There are some things that you can’t do while you are working with classes in programming.
Let’s learn about those aspects and learn how to solve this error.
Class Type Redefinition in C++
When you define a class twice with the same name, the C++ compiler will throw an error: class type redefinition
. For instance, take a look at the following code.
#include<iostream>
using namespace std;
// #include student.h
//when you define a class twice with same name then you will get an error class type redefinition
class student
{
};
class student
{
};
// // the best way to solve the error is to define classes with different name
// class student_
// {
// };
So, you can’t define two classes with the same name. The best way to avoid this error is to create classes with different names.
#include<iostream>
using namespace std;
// #include student.h
//when you define a class twice with same name then you will get an error class type redefinition
class student
{
};
// // the best way to solve the error is to define classes with a different name
class student_
{
};
In the same way, we can’t define the same name variables, but we can define the same name functions, and that concept is called function overloading.
Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.
Related Article — C++ Class
|
|
|
Правила раздела Visual C++ / MFC / WTL (далее Раздела)
Ошибка ‘class’ type redefinition
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Привет! |
Flex Ferrum |
|
Это означает, что класс с таким именем у тебя уже есть. |
SVK |
|
а в своих хедерах рекомендовано делать так: #ifndef _MY_HEADER<такой-то>_H_ <описание> #endif /*_MY_HEADER<такой-то>_H_*/ правда VC это делает автоматом |
eprup |
|
для VC еще есть #pragma once |
darkgraf |
|
Junior Рейтинг (т): 0 |
Цитата SVK, 07.03.03, 15:09:31 а в своих хедерах рекомендовано делать так: #ifndef _MY_HEADER<такой-то>_H_ <описание> #endif /*_MY_HEADER<такой-то>_H_*/ правда VC это делает автоматом Никогда так не делай. — Запрещено начинать имя со знака подчеркивания Удачи. |
SVK |
|
Цитата darkgraf, 11.03.03, 15:23:51 — Запрещено начинать имя со знака подчеркивания Данные запреты имеют разумную аргументацию? |
SirVaulterScoff |
|
Цитата Данные запреты имеют разумную аргументацию? ИМХО да. имена начинающиеся со знака подчёркивания зарезервированы стандартом ANSI для расширения компиляторов, т.е. обозвав свой макрос как-нить #define _BLAH_BLAH_BLAH есть риск, что в новой версии компилятора это будет какой-то используемый макрос |
SVK |
|
Цитата SirVaulterScoff, 11.03.03, 18:42:14 ИМХО да. имена начинающиеся со знака подчёркивания зарезервированы стандартом ANSI для расширения компиляторов, т.е. обозвав свой макрос как-нить #define _BLAH_BLAH_BLAH есть риск, что в новой версии компилятора это будет какой-то используемый макрос Нее.. с этим все ясно, я уж думал что там чавой-то жутко страшное |
darkgraf |
|
Junior Рейтинг (т): 0 |
Безусловно. Классический пример: <br>#include <tchar.h><br>int main()<br>{<br> int _T(5);<br>}<br> попытается понять _T(5) как херню для работы с UNICODE, объявленную в tchar.h. Конкретно (17.4.3.1.2/1): Руслан |
darkgraf |
|
Junior Рейтинг (т): 0 |
Цитата SVK , 11.03.03, 18:53:20 Нее.. с этим все ясно, я уж думал что там чавой-то жутко страшное Есть мнение, что компилятор может вообще по-другому интерпретировать имена, попадающие в зарезервированный список. Руслан |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Visual C++ / MFC / WTL
- Следующая тема
[ Script execution time: 0,0290 ] [ 16 queries used ] [ Generated: 9.02.23, 12:21 GMT ]
- Remove From My Forums
-
Question
-
Hi,
I am trying to Use a C static Library (self creation) in a c++ project,however ended up with ‘struct’ redefinition.Here you can have a look.
I tried to include guards in header files but didn’t work well.
Any ideas would be appreciated.
All replies
-
Maybe you include the header wrong. Show us the header of your library and the include statement in your source.
It looks like you include the header many times. Do you have #pragma once in your headers?
Regards, Guido
-
Than you for your reply.
Yes, have included #pragma once also.
Here are my header and .c file,where i have created static library.
Here you can see the cpp files,which are using static library.
Note: There are some other supporting headers too.
Regards
venkat
-
Edited by
Friday, June 9, 2017 10:20 AM
-
Edited by
-
Note: There are some other supporting headers too.
Well, what about these other header files? Do they have include guards?
David Wilkinson | Visual C++ MVP
-
Yes,All the headers have the guards,however i don’t know the exact reason.
-
Yes,All the headers have the guards,however i don’t know the exact reason.
Reason for what? The reason header files should have include guards (or #pragma once) is so they do not get included more than once in the same translation unit.
David Wilkinson | Visual C++ MVP
-
You don’t need #pragma once in the c or cpp files because the source files are not included anywhere.
You must only insert #pragma once in every header file at the top of the file. That’s enough.
If you use #include «stdafx.h» in your source files, you must put it as the first include file.
Then you compile again. The compiler will tell you, in which file the redefinition comes. Check the includes in this file.
Regards, Guido
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 |
#include <QtGui> #include <QtWebKit> #include "mainwindow.h" #include "ftpview.h" #include "ftpreply.h" MainWindow::MainWindow(const QUrl& url) { progress = 0; QFile file; file.setFileName(":/jquery.min.js"); file.open(QIODevice::ReadOnly); jQuery = file.readAll(); file.close(); QNetworkProxyFactory::setUseSystemConfiguration(true); view = new FtpView(this); view->setUrl(url); connect(view, SIGNAL(loadFinished(bool)), SLOT(adjustLocation())); connect(view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle())); connect(view, SIGNAL(loadProgress(int)), SLOT(setProgress(int))); connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool))); locationEdit = new QLineEdit(this); locationEdit->setSizePolicy(QSizePolicy::Expanding, locationEdit->sizePolicy().verticalPolicy()); connect(locationEdit, SIGNAL(returnPressed()), SLOT(changeLocation())); QToolBar *toolBar = addToolBar(tr("Navigation")); toolBar->addAction(view->pageAction(QWebPage::Back)); toolBar->addAction(view->pageAction(QWebPage::Forward)); toolBar->addAction(view->pageAction(QWebPage::Reload)); toolBar->addAction(view->pageAction(QWebPage::Stop)); toolBar->addWidget(locationEdit); QMenu *viewMenu = menuBar()->addMenu(tr("&File")); QAction* viewSourceAction = new QAction("Save As TXT", this); connect(viewSourceAction, SIGNAL(triggered()), SLOT(viewSource())); viewMenu->addAction(viewSourceAction); QMenu *pageMenu = menuBar()->addMenu(tr("&Page")); QAction* pageSourceAction = new QAction("Bookmark this page", this); connect(pageSourceAction, SIGNAL(triggered()), SLOT(bookmarkThisPage())); pageMenu->addAction(pageSourceAction); bookMenu = menuBar()->addMenu(tr("&Bookmarks")); setCentralWidget(view); setUnifiedTitleAndToolBarOnMac(true); } //! [3] QLineEdit* MainWindow::getLine() { return locationEdit; } void MainWindow::viewSource() { QNetworkAccessManager* accessManager = view->page()->networkAccessManager(); QNetworkRequest request(view->url()); QNetworkReply* reply = accessManager->get(request); connect(reply, SIGNAL(finished()), this, SLOT(slotSourceDownloaded())); } void MainWindow::bookmarkThisPage() { QString empty(""); QUrl url(locationEdit->text()); int flag = 0; for (int i = 0; i < bookmarks.size(); i++ ) { if (bookmarks[i].encodedPath() == url.encodedPath()) flag = 1; } if ((flag == 0) && (locationEdit->text().compare(empty) != 0)) { bookmarks.insert(0,url); QAction* pageSourceAction = new QAction(url.toString(), this); connect(pageSourceAction, SIGNAL(triggered()), SLOT(goToBookmark())); bookMenu->addAction(pageSourceAction); } } void MainWindow::goToBookmark() { QAction *a = qobject_cast<QAction *>(sender()); QString s = a->text(); QUrl url(s); view->load(url); view->setFocus(); } void MainWindow::saveAsHtml() { ; } void MainWindow::slotSourceDownloaded() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(const_cast<QObject*>(sender())); QString s1; QString temp = locationEdit->text(); int flag = 0; for (int i = 0; i < temp.size(); i++) { if ((temp[i] == '/') && (temp[i-1] == '/')) { for (int j = i+1; j < temp.size(); j++) { if (temp[j] == '/') break; else s1[j-i] = temp[j]; } } } s1 = s1 + ".txt"; QFile file(s1); file.open(QFile::WriteOnly); QTextStream ts(&file); ts << view->page()->currentFrame()->toHtml(); file.close(); reply->deleteLater(); } void MainWindow::adjustLocation() { locationEdit->setText(view->url().toString()); } void MainWindow::changeLocation() { QUrl url = QUrl(locationEdit->text()); QString s = QString(locationEdit->text()); if ((s[0] == 'f') && (s[1] == 't') && (s[2]=='p')) { view->setUrl(url); view->setFocus(); } } void MainWindow::adjustTitle() { if (progress <= 0 || progress >= 100) setWindowTitle(view->title()); else setWindowTitle(QString("%1 (%2%)").arg(view->title()).arg(progress)); } void MainWindow::setProgress(int p) { progress = p; adjustTitle(); } void MainWindow::finishLoading(bool) { progress = 100; adjustTitle(); view->page()->mainFrame()->evaluateJavaScript(jQuery); } //! [6] //! [7] void MainWindow::highlightAllLinks() { QString code = "$('a').each( function () { $(this).css('background-color', 'yellow') } )"; view->page()->mainFrame()->evaluateJavaScript(code); } //! [7] //! [8] void MainWindow::removeGifImages() { QString code = "$('[src*=gif]').remove()"; view->page()->mainFrame()->evaluateJavaScript(code); } void MainWindow::removeInlineFrames() { QString code = "$('iframe').remove()"; view->page()->mainFrame()->evaluateJavaScript(code); } void MainWindow::removeObjectElements() { QString code = "$('object').remove()"; view->page()->mainFrame()->evaluateJavaScript(code); } void MainWindow::removeEmbeddedElements() { QString code = "$('embed').remove()"; view->page()->mainFrame()->evaluateJavaScript(code); } //! [9] |
Один из файлов заголовков выглядит следующим образом:
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
Когда я пытаюсь скомпилировать проект, я получаю сообщение об ошибке
error C2011: 'AAA' : 'class' type redefinition
Нигде в моей программе не было переопределено класс AAA
. Как это исправить?
07 сен. 2014, в 21:06
Поделиться
Источник
3 ответа
Измените код на что-то вроде этого:
#ifndef AAA_HEADER
#define AAA_HEADER
#include "stdafx.h"
class AAA
{
public:
std::string strX;
std::string strY;
};
#endif
Если вы включите этот файл заголовка более одного раза в некоторый исходный файл, включите защитники, чтобы заставить компилятор генерировать класс только один раз, чтобы он не выдавал ошибку class redefinition
.
Ashot
07 сен. 2014, в 19:34
Поделиться
Добавление
#pragma once
в верхней части вашего файла AAA.h следует позаботиться о проблеме.
как это
#include "stdafx.h"
#pragma once
class AAA
{
public:
std::string strX;
std::string strY;
};
empty
07 июнь 2016, в 18:28
Поделиться
В дополнение к предлагаемым включенным защитным устройствам вам нужно переместить #include «stdafx.h» из заголовка. Поместите его в начало файла cpp.
ScottMcP-MVP
07 сен. 2014, в 22:03
Поделиться
Ещё вопросы
- 1Отправить запрос с использованием resttemplate, но иметь 401 несанкционированный
- 1Проверка графов Java-объектов
- 0Преобразовать целое число из DB2 в дату с интервалом дня для вставки MySQL
- 0JQuery AJAX вызов с codeigniter
- 1Создание объекта с помощью отражения с анонимным типом
- 0Ошибка с удалением класса «липкий» из «nav» после выполнения симпатичной библиотеки фотографий
- 1Windowlicker не работает на OS X
- 1расшифровка и чтение
- 1Насмешливый PrintQueue в .NET
- 0Предотвратить автоматическое обновление с помощью php?
- 1Заставьте Android Phone Call Audio пройти через A2DP Bluetooth-соединение
- 0Как получить доступ к device_vector из функтора
- 1Апплет не начнет использовать апплет-бегун из Intellij Idea
- 1Утечка памяти Android, без статических переменных
- 0Прокрутка с использованием Javascript внутри элемента переполнения
- 0API-интерфейс Node.js с Express & MySQL — получение количества записей, номера страницы и т. Д.
- 1Подходящий способ передать экземпляр класса другим классам (Java)
- 0Получить массив данных от angularjs
- 1Поток: генерирует тип объекта «Y» из типа объекта «X», где «Y» имеет все те же ключи, что и «X», но все типы являются строковыми
- 0Угловая директива множественных входов одной модели
- 0Как я могу отправить ссылку на угловую директиву модели, а не скопировать
- 0Получить все значения из одного столбца в MySQL PDO
- 0Проблема с компиляцией функции, которая возвращает строку &
- 0Добавление метода поиска в jTable (jquery)
- 0JQuery не селектор не работает на активный класс
- 0Могу ли я сделать C / C ++ #defines закрытым?
- 1Получить поля в Java-классе методом Getter с аннотацией
- 0PHP-код, чтобы дать позицию в соответствии с их баллами (1, 2, 3, 3, 5)
- 1Android OutOfMemoryError: размер растрового изображения превышает бюджет виртуальной машины
- 0Как предотвратить расширение строки таблицы CSS до родительской высоты
- 0Безопасно ли отображать сообщения об ошибках SQL на вашем сайте? (MySQLi)
- 0как вернуть большое число с помощью консольного приложения c ++
- 0Читайте веб-сайт, как пользователи видят его с HttpComponents
- 0Как обновить запись в БД с помощью CodeIgniter?
- 0Функция маршрутизатора узла .delete возвращает 404 Not Found?
- 0Проблемы с возвышенным текстом и угловым JS
- 0Среднее число нечетных клеток?
- 0как проверить данные по тексту?
- 1Не удалось загрузить myapp.apk
- 0Как получить столбец (NEW. {{Col_name}}), если его имя хранится в переменной — MySQL
- 1Android редактировать текст
- 0конструктор создает объект, но не присваивает ему значения
- 1Проблемы с окном и уровнем изображения Dicom (иногда)
- 0Оператор << Перегрузка не работает правильно для комплексных чисел
- 1Проблема использования градиентов политик с Tensorflow для обучения агента игры в понг
- 1Пользовательские свойства файла в Dropbox Core API?
- 1C # Task.continu, который зависит от предыдущего Task.Result
- 0Метод JQuery не работает с кэшированными дочерними объектами
- 1Как избежать возобновления работы приложения на экране блокировки
- 1Rails will_paginate бесконечная прокрутка с массивом, который отбрасывает первые 3 элемента