Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «int main(void)» уже имеет текст реализации (C2084)
Source.cpp
#include <iostream>
#include <Windows.h>
#include "func.h"
using namespace std;
void Interface();
int main() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
Interface();
}
func.h
#pragma once
#include "Source.cpp"
void Interface() {
int quest;
while (true) {
cout << "1. Открыть базу" << endl;
cout << "2. Закрыть программу" << endl;
cout << "Номер пути _b";
cin >> quest;
if (quest = 1) {
cout << "Открыто!";
}
else if (quest = 2) {
cout << "Закрыто!";
}
}
}
задан 1 янв 2018 в 19:25
1
У вас неверное понимание, что должно находиться в заголовочном файле, а что — в .cpp
.
В заголовочном файле располагайте объявления, а определения — в cpp-файле. В заголовочном файле располагаются также inline-реализации, шаблоны и т.п. вещи, но в вашем случае все, что следует разместить в func.h
— это
void Interface();
Все остальное — в .cpp
-файлах, и не включать .cpp
-файлы с помощью директивы #include
— иначе вы получаете нарушение правила одного определения.
ответ дан 1 янв 2018 в 19:50
HarryHarry
210k15 золотых знаков115 серебряных знаков224 бронзовых знака
4
Dmitriy1342 1 / 1 / 0 Регистрация: 07.02.2012 Сообщений: 37 |
|||||||||
1 |
|||||||||
Ошибка: Функция уже имеет текст реализации.13.02.2012, 14:54. Показов 20250. Ответов 7 Метки нет (Все метки)
Вылезает данная ошибка error C2084: функция «double hypot(double,double)» уже имеет текст реализации. Это мой вариант программы, пробовал скопировать текст c учебника — не помогло. Что делать?
__________________
1 |
5053 / 3114 / 271 Регистрация: 11.11.2009 Сообщений: 7,045 |
|
13.02.2012, 15:00 |
2 |
Dmitriy1342, переименуйте функцию.
1 |
return (true); 1976 / 1111 / 221 Регистрация: 19.04.2011 Сообщений: 2,345 |
|
13.02.2012, 15:02 |
3 |
уже имеет текст реализации Русским по белому написано, функция с таким именем и насколько помнится с таким же содержанием уже описана в math.h
2 |
Заблокирован |
||||
13.02.2012, 17:13 |
4 |
|||
Dmitriy1342, а можете не менять название а просто записать функцию в вашем собственном namespace ИМХО все так любят ставить std:: почему бы не воспользоваться рефакторингом в свою пользу!
PS:Раз уж мы хотим стать «продвинутыми дядьками», то почему бы по продвинутому не действовать? Миниатюры
0 |
Dmitriy1342 1 / 1 / 0 Регистрация: 07.02.2012 Сообщений: 37 |
||||
13.02.2012, 17:35 [ТС] |
5 |
|||
Dmitriy1342, а можете не менять название а просто записать функцию в вашем собственном namespace ИМХО все так любят ставить std:: почему бы не воспользоваться рефакторингом в свою пользу!
PS:Раз уж мы хотим стать «продвинутыми дядьками», то почему бы по продвинутому не действовать? Хм, а что такое system(«chcp 1251»); ?
0 |
Заблокирован |
|
13.02.2012, 17:39 |
6 |
chcp — изменение кодовой страницы cmd.exe Очень часто нужно, чтобы вместо кодовой страницы cp866 (заданной по-умолчанию) данные были в cp1251 (команда chcp 1251) или в utf8 (chcp 65001).
0 |
Заблокирован |
|
13.02.2012, 17:41 |
7 |
Хм, а что такое system(«chcp 1251»); ? — да єто руссификация на старых компиляторах, вместо неё поставь + в хедеры #include <locale>
setlocale (LC_ALL, «Russian»); видишь же я закоментил её…
1 |
1 / 1 / 0 Регистрация: 07.02.2012 Сообщений: 37 |
|
13.02.2012, 17:42 [ТС] |
8 |
А, понятно, спасибо.
0 |
Может кто-нибудь помочь мне разобраться с этой ошибкой
У меня есть два файла под исходными файлами в Visual Studio 2013 Express
main.cpp и Variables.cpp
ниже приведены коды
ОШИБКА СКРИНШОТА
ПРЕДУПРЕЖДЕНИЕ И ОШИБКА СКРИНШОТА
main.cpp
#include <iostream>
#include "Variables.cpp"using namespace std;
int main()
{
int a = 3;
cout << "Hello World" << endl;
cout << "The value of a: " << a << endl;
getchar();
return 0;
}
Variables.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Declaring Variables
int a = 3;
float b = 33.3;
double c = 223.334;
char d = 'i';
string e = "This is a test text !";
//Printing
cout << "The value of a: " << a << endl;
cout << "The value of b: " << b << endl;
cout << "The value of c: " << c << endl;
cout << "The value of d: " << d << endl;
cout << "The value of e: " << e << endl;
//Show Msg
getchar();
return 0;
}
ошибка
Предупреждение 1
предупреждение C4305: «инициализация»: усечение с «double» до «float» c: users iifra Documents visual studio 2013 projects testproject001 testproject001 variables.cpp 11 1 TestProject001
Ошибка 2
ошибка C2084: функция ‘int main (void)’ уже имеет тело c: users iifra Documents visual studio 2013 projects testproject001 testproject001 main.cpp 6 1 TestProject001
Предупреждение 3
предупреждение C4305: «инициализация»: усечение с «double» до «float» c: users iifra Documents visual studio 2013 projects testproject001 testproject001 variables.cpp 11 1 TestProject001
-3
Решение
Изменить название функции main()
присутствует в Variables.cpp для любого другого имени.
Вы не можете использовать две функции main () в одном проекте, потому что ваша ОС находит основную функцию, присутствующую в вашем проекте, когда вы запускаете проект. И здесь ОС путает, какую основную функцию вызывать первой.
1
Другие решения
Это вопрос для начинающих. Два аспекта:
- Вы можете иметь только 1 функцию «main», так как «main» является особенной (точка входа)
- вы можете использовать несколько исходных файлов; используйте заголовок для объявлений и источник для определений
например.:
основной источник:
// main.cpp
#include <iostream>
#include "variables.hpp"
int main()
{
int a = 3;
std::cout << "Hello World" << std::endl;
std::cout << "The value of a: " << a << std::endl;
//invoke f
f();
//getchar();
return 0;
}
Заголовок переменных:
//variables.hpp
void f();
источник переменных:
//variables.cpp
#include <iostream>
#include "variables.hpp"
void f()
{
std::cout << "Bla" << std::endl;
}
Компилятор будет обрабатывать их как два модуля перевода и создает два файла obj (то есть main.obj и variables.obj), а компоновщик объединит их вместе как один exe.
Вы используете Visual Studio. Поместите заголовочные файлы в папку заголовка, а файлы cpp — в исходную папку.
0
Перейти к контенту
Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «int main(void)» уже имеет текст реализации (C2084)
Source.cpp
#include <iostream>
#include <Windows.h>
#include "func.h"
using namespace std;
void Interface();
int main() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
Interface();
}
func.h
#pragma once
#include "Source.cpp"
void Interface() {
int quest;
while (true) {
cout << "1. Открыть базу" << endl;
cout << "2. Закрыть программу" << endl;
cout << "Номер пути _b";
cin >> quest;
if (quest = 1) {
cout << "Открыто!";
}
else if (quest = 2) {
cout << "Закрыто!";
}
}
}
задан 1 янв 2018 в 19:25
1
У вас неверное понимание, что должно находиться в заголовочном файле, а что — в .cpp
.
В заголовочном файле располагайте объявления, а определения — в cpp-файле. В заголовочном файле располагаются также inline-реализации, шаблоны и т.п. вещи, но в вашем случае все, что следует разместить в func.h
— это
void Interface();
Все остальное — в .cpp
-файлах, и не включать .cpp
-файлы с помощью директивы #include
— иначе вы получаете нарушение правила одного определения.
ответ дан 1 янв 2018 в 19:50
HarryHarry
210k15 золотых знаков114 серебряных знаков224 бронзовых знака
4
- Remove From My Forums
-
Question
-
Hi All,
I’m migrating an existing project from vs 6.0 to vs 2008. I get the below error,
» error C2084: function ‘tstring::tstring(void)’ already has a body «
Error Code in tstring.cpp file:
tstring::tstring() { }
As the error message suggest there is another constructor for the same function in the header file tstring.h:
// Constructors inline tstring::tstring() : base_class() { }
I don’t understand why «tstring::tstring()» constructor is there twice in cpp and h file and how to fix this error. Shall I remove tstring::tstring(){} completely?, that way a duplicate entry is removed.. Any help to fix this issue is
greatly appreciated. Thanks in advance!P.S: This error does not occur when compiled in vs 6.0
Regards,
Ankush
Answers
-
On 19/02/2014 12:29, ankushkumar wrote:
» error C2084: function ‘tstring::tstring(void)’ already has a body/ /»
Error Code in tstring.cpp file:tstring::tstring() { }
As the error message suggest there is another constructor for the same function in the header file tstring.h:
// Constructors inline tstring::tstring() : base_class() { }
I don’t understand why «tstring::tstring()» constructor is there twice in cpp and h file and how to fix this error. Shall I remove tstring::tstring(){} completely?, that way a duplicate entry is removed..
You may want to remove one of the two. Considering that the body is just empty, it seems a good candidate to be inlined, so I’d just use this in the header file:
inline tstring::tstring() { }
I’m not sure about the base_class() initialization… should it be just automatic?
P.S: This error does not occur when compiled in vs 6.0
Note that the C++ compiler that ships with VS2008 is better than the one in VC6 (VS2008’s C++ compiler conforms to the C++98/03 standard, VC6 compiler doesn’t).
So, it’s very possible that the C++ compiler that comes with VS2008 emits several errors that the VC6 compiler ignored.Giovanni
- Marked as answer by
Tuesday, February 25, 2014 8:34 AM
- Marked as answer by
I receive the following error:
1> resistor.cpp(7): error C2084: function 'Resistor::Resistor(int,std::string,double,int [])' already has a body
1> resistor.h(25) : see previous definition of '{ctor}'
With every single one of my class functions, even though in resistor.h I have don’t have any empty implementations:
Resistor.h:
class Resistor
{
private:
int rIndex;
double resistance; // resistance (in Ohms)
string name; // C++ string holding the label
int endpointNodeIDs[2]; // IDs of nodes it attaches to
public:
Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2]);
}
Resistor.cpp:
Resistor::Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2])
{
if (nodeArray[endpoints_[0]].addResistor(rIndex_) && NodeArray[endpoints_[1]].addResistor(rIndex_))
{
rIndex = rIndex_;
name = name_;
resistance = resistance_;
endpointNodeIDs[0] = endpoints_[0];
endpointNodeIDs[1] = endpoints_[1];
}
return;
}
etc. for each of my class functions
Can anybody help me?
p.s. I also receive the following error, once again for every function in resistor class (except for the constructor, mysteriously):
1>rparser.cpp(301): error C2264: 'Resistor::setIndex' : error in function definition or declaration; function not called
I receive the following error:
1> resistor.cpp(7): error C2084: function 'Resistor::Resistor(int,std::string,double,int [])' already has a body
1> resistor.h(25) : see previous definition of '{ctor}'
With every single one of my class functions, even though in resistor.h I have don’t have any empty implementations:
Resistor.h:
class Resistor
{
private:
int rIndex;
double resistance; // resistance (in Ohms)
string name; // C++ string holding the label
int endpointNodeIDs[2]; // IDs of nodes it attaches to
public:
Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2]);
}
Resistor.cpp:
Resistor::Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2])
{
if (nodeArray[endpoints_[0]].addResistor(rIndex_) && NodeArray[endpoints_[1]].addResistor(rIndex_))
{
rIndex = rIndex_;
name = name_;
resistance = resistance_;
endpointNodeIDs[0] = endpoints_[0];
endpointNodeIDs[1] = endpoints_[1];
}
return;
}
etc. for each of my class functions
Can anybody help me?
p.s. I also receive the following error, once again for every function in resistor class (except for the constructor, mysteriously):
1>rparser.cpp(301): error C2264: 'Resistor::setIndex' : error in function definition or declaration; function not called
- Forum
- Beginners
- error c2084
error c2084
#include <Windows.h>
#include <iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
void classRec(); void end(); void editRec(); void gotoxy(int x,int y);
;
void menu()
{
char ch;
do
{ cout<<«nnntMAIN MENU»;
cout<<«nnt1. CLASS RECORD»;
cout<<«nnt2. EDIT RECORDS»;
cout<<«nnt3. HELP»;
cout<<«nnt4. EXIT»;
cout<<«nntPlease Select Your Option (1-3): «;
k:
cin>> ch;
switch(ch)
{
case ‘1’: classRec();
break;
case ‘2’: editRec();
break;
case ‘3’: end();
break;
default :
gotoxy(8,15);
cout<<«Please enter a valid choice: «;
goto k;
}
}while(ch!=’3′);
system(«cls»);
system(«pause>0»);
}
I can’t run my program. It says that there’s an error,error C2084: function ‘void menu(void)’ already has a body. How can I solve this? Please help me. Thank you. =)
It would be more helpful if you showed the exact error the compiler produced. It will name one or more files, so we’ll need to those too (with their names).
Error 1 error C2084: function ‘void menu(void)’ already has a body c:userspaulinedocumentsvisual studio 2010projectsclassrecordclassrecordmenu.h 11
Please help me. I’m just a beginner in programming and I badly needed to finish this program. Thank you so much. =)
And what’s in menu.h?
And why is there no reference to menu.h in the posted code?
Last edited on
Topic archived. No new replies allowed.
Вопрос:
Я не мог понять, что мне нужно сделать, чтобы исправить эту ошибку или найти что-либо на этом веб-сайте. В основном я получаю ошибку C2084: функция “Калькулятор :: GUI :: GUI (void)” уже имеет тело. Все, что у меня есть, – это форма окна, называемая GUI, добавленная в приложение Win32, калькулятор.
В GUI.h:
#pragma once
namespace Calculator {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for GUI
/// </summary>
public ref class GUI : public System::Windows::Forms::Form
{
void AddControls();
public:
GUI()
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
и в GUI.cpp
#include "GUI.h"
namespace Calculator {
GUI::GUI()
{
}
void DrawButtons();
void DrawLabels();
void GUI::AddControls()
{
DrawButtons();
DrawLabels();
}
Я получил то, что хотел работать, поместив все в файл GUI.h, но хотел иметь код метода внутри.cpp файла.
Лучший ответ:
Измените заголовок следующим образом:
public ref class GUI : public System::Windows::Forms::Form
{
void AddControls();
public:
GUI();
}
Вы видите, что заголовок должен содержать только декларации и вносить реализацию в cpp.
- Forum
- Beginners
- error c2084
error c2084
#include <Windows.h>
#include <iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
void classRec(); void end(); void editRec(); void gotoxy(int x,int y);
;
void menu()
{
char ch;
do
{ cout<<«nnntMAIN MENU»;
cout<<«nnt1. CLASS RECORD»;
cout<<«nnt2. EDIT RECORDS»;
cout<<«nnt3. HELP»;
cout<<«nnt4. EXIT»;
cout<<«nntPlease Select Your Option (1-3): «;
k:
cin>> ch;
switch(ch)
{
case ‘1’: classRec();
break;
case ‘2’: editRec();
break;
case ‘3’: end();
break;
default :
gotoxy(8,15);
cout<<«Please enter a valid choice: «;
goto k;
}
}while(ch!=’3′);
system(«cls»);
system(«pause>0»);
}
I can’t run my program. It says that there’s an error,error C2084: function ‘void menu(void)’ already has a body. How can I solve this? Please help me. Thank you. =)
It would be more helpful if you showed the exact error the compiler produced. It will name one or more files, so we’ll need to those too (with their names).
Error 1 error C2084: function ‘void menu(void)’ already has a body c:userspaulinedocumentsvisual studio 2010projectsclassrecordclassrecordmenu.h 11
Please help me. I’m just a beginner in programming and I badly needed to finish this program. Thank you so much. =)
And what’s in menu.h?
And why is there no reference to menu.h in the posted code?
Last edited on
Topic archived. No new replies allowed.
Форум программистов Vingrad
Модераторы: bsa |
Поиск: |
|
Ошибка |
Опции темы |
newnik |
|
||||
Новичок Профиль Репутация: нет
|
В этой программе пишет такую ошибку
Модератор: Не забываем пользоваться кнопочкой «Код» Это сообщение отредактировал(а) bsa — 27.2.2011, 19:24 |
||||
|
|||||
volatile |
|
||
Эксперт Профиль Репутация: 16
|
Перевести не пробовали. |
||
|
|||
newnik |
|
||||
Новичок Профиль Репутация: нет
|
и что тогда сделать надо? |
||||
|
|||||
volatile |
|
||
Эксперт Профиль Репутация: 16
|
Надо выбрать какую вы будете использовать. |
||
|
|||
bsa |
|
||
Эксперт Профиль
Репутация: 85
|
newnik, рекомендую почитать Оформление кода ——————— Правильно заданный вопрос — половина ответа |
||
|
|||
|
Правила форума «C/C++: Для новичков» | |
|
Запрещается! 1. Публиковать ссылки на вскрытые компоненты 2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa. |
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | C/C++: Для новичков | Следующая тема » |