Dmitriy1342 1 / 1 / 0 Регистрация: 07.02.2012 Сообщений: 37 |
|||||||||
1 |
|||||||||
Ошибка: Функция уже имеет текст реализации.13.02.2012, 14:54. Показов 21884. Ответов 7 Метки нет (Все метки)
Вылезает данная ошибка error C2084: функция «double hypot(double,double)» уже имеет текст реализации. Это мой вариант программы, пробовал скопировать текст c учебника — не помогло. Что делать?
1 |
5054 / 3115 / 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 |
Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «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
215k15 золотых знаков117 серебряных знаков228 бронзовых знаков
4
Перейти к контенту
Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «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.
У вас неверное понимание, что должно находиться в заголовочном файле, а что — в .cpp
.
В заголовочном файле располагайте объявления, а определения — в cpp-файле. В заголовочном файле располагаются также inline-реализации, шаблоны и т.п. вещи, но в вашем случае все, что следует разместить в func.h
— это
void Interface();
Все остальное — в .cpp
-файлах, и не включать .cpp
-файлы с помощью директивы #include
— иначе вы получаете нарушение правила одного определения.
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2084 |
Compiler Error C2084 |
11/04/2016 |
C2084 |
C2084 |
990b107f-3721-4851-ae8b-4b69a8c149ed |
Compiler Error C2084
function ‘function‘ already has a body
The function has already been defined.
Before Visual Studio 2002,
-
The compiler would accept multiple template specializations that resolved to the same actual type, although the additional definitions would never be available. The compiler now detects these multiple definitions.
-
__int32
andint
were treated as separate types. The compiler now treats__int32
as a synonym forint
. This means that the compiler detects multiple definitions if a function is overloaded on both__int32
andint
and gives an error.
Example
The following sample generates C2084:
// C2084.cpp void Func(int); void Func(int) {} // define function void Func(int) {} // C2084 second definition
To correct this error, remove the duplicate definition:
// C2084b.cpp // compile with: /c void Func(int); void Func(int) {}