Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «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
214k15 золотых знаков117 серебряных знаков229 бронзовых знаков
4
2 / 2 / 0 Регистрация: 03.02.2014 Сообщений: 28 |
|
1 |
|
программа выдает ошибку, как ее поправить09.02.2014, 22:38. Показов 1961. Ответов 13
Добрый вечер! программа выдает ошибку: функция «int main(void)» уже имеет текст реализации
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
09.02.2014, 22:38 |
Ответы с готовыми решениями: Программа которая выдает платформу компьютера выдает ошибку interface uses При решении программа выдаёт значение функции, равное 0 или выдаёт ошибку. Что не так? long Fact(short…
У меня не выдает ошибку, но программа действует не так как я хочу. Глаза должны двигаться за мышкой,но этого не происход procedure… 13 |
22 / 22 / 7 Регистрация: 01.12.2013 Сообщений: 93 |
|
09.02.2014, 22:39 |
2 |
strannik11, какой компилятор используйте? Покажите код
0 |
strannik11 2 / 2 / 0 Регистрация: 03.02.2014 Сообщений: 28 |
||||
09.02.2014, 22:41 [ТС] |
3 |
|||
0 |
17410 / 9246 / 2260 Регистрация: 30.01.2014 Сообщений: 16,169 |
|
09.02.2014, 22:43 |
4 |
Так у вас реально два main`а
1 |
strannik11 2 / 2 / 0 Регистрация: 03.02.2014 Сообщений: 28 |
||||||||||||
09.02.2014, 22:55 [ТС] |
5 |
|||||||||||
поправил, появился новый вопрос, почему у меня из исходного текстовика улетел весь текст? и во второй не прошло не одной записи? Добавлено через 8 минут
заменил имя файла, но во второй должна записаться строка:
подскажите почему ничего не происходит?
0 |
DrOffset 17410 / 9246 / 2260 Регистрация: 30.01.2014 Сообщений: 16,169 |
||||
09.02.2014, 23:40 |
6 |
|||
подскажите почему ничего не происходит? У вас std::string stroc первый раз объявлена внутри условия else, по правилам С++ ее время жизни ограничено блоком. Ниже вы создали еще одну (другую!) переменную stroc, она естественно пуста. Поправить можно перенеся объявление выше:
1 |
strannik11 2 / 2 / 0 Регистрация: 03.02.2014 Сообщений: 28 |
||||
10.02.2014, 13:37 [ТС] |
7 |
|||
поправил так как вы посоветовали, но запись почему то так и не происходит, не могу понять почему?
0 |
DrOffset 17410 / 9246 / 2260 Регистрация: 30.01.2014 Сообщений: 16,169 |
||||||||
10.02.2014, 15:11 |
8 |
|||||||
поправил так как вы посоветовали, но запись почему то так и не происходит, не могу понять почему? Ошибка та же. Объявление должно быть одно, а у вас их опять два.
заменить на
1 |
2 / 2 / 0 Регистрация: 03.02.2014 Сообщений: 28 |
|
10.02.2014, 15:26 [ТС] |
9 |
DrOffset, спасибо вам большое за советы, но эту ошибку исправил уже сам)) очень помогли мне. Добавлено через 4 минуты
0 |
DrOffset 17410 / 9246 / 2260 Регистрация: 30.01.2014 Сообщений: 16,169 |
||||
10.02.2014, 19:47 |
10 |
|||
как мне сделать так что бы моя программа не прибавляла в счетчике повторные слова, что бы например, слово «привет» считалось 1 раз, а потом программа пропускала бы его и шла дальше. Мне кажется самый просто способ для вас это использовать std::set. Добавлять туда слова из файла, дубликаты отсеятся.
0 |
2 / 2 / 0 Регистрация: 06.11.2011 Сообщений: 68 |
|
10.02.2014, 21:30 |
11 |
что ты мучаешься ? просто используй void main() и не мучайся))
0 |
17410 / 9246 / 2260 Регистрация: 30.01.2014 Сообщений: 16,169 |
|
10.02.2014, 21:45 |
12 |
что ты мучаешься ? просто используй void main() и не мучайся)) Такая форма main запрещена в С++. 3.6.1/2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall
0 |
2 / 2 / 0 Регистрация: 06.11.2011 Сообщений: 68 |
|
10.02.2014, 21:49 |
13 |
ошибаешься , она часто используется ….
0 |
17410 / 9246 / 2260 Регистрация: 30.01.2014 Сообщений: 16,169 |
|
11.02.2014, 00:27 |
14 |
ошибаешься , она часто используется …. Любой современный компилятор по-умолчанию выдаст ошибку. Кроме VS, которая это пропустит (расширение компилятора), но это исключительно ее личное дело. Программист, пишущий портабельный код, не должен на это закладываться. А тот, который не пишет, все равно должен про это знать.
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.
Может кто-нибудь помочь мне разобраться с этой ошибкой
У меня есть два файла под исходными файлами в 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 золотых знаков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
Опции темы |
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++: Для новичков | Следующая тема » |