Ошибка компилятора c2084

Я видел это по всему сайту, и до сих пор ничто не смогло решить мою проблему. это единственная ошибка, которая у меня есть, и я не знаю, как это исправить. Я пытался комментировать различные разделы кода, просто чтобы посмотреть, что происходит, и все еще ничего, кроме ошибок. Что здесь происходит?

Она тоже ошибка сборки

ошибка C2084: функция ‘HeroProfile :: HeroProfile (void)’ уже имеет тело

main.cpp

#include <iostream>
#include <string>

#include "HeroProfile.h"
using namespace std;

int main()
{
string name;
int race;
double weight;

cout << "Enter your Hero's name:";
cin>> name;
cout << "Enter your Hero's Race (1:Elf 2:Human 3 Dwarf)";
cin >> race;
cout << "Enters your Hero's weight ( in pounds):";
cin >> weight;

HeroProfile Hero_1(name, race, weight);

cout << endl << "hero's Name: " << Hero_1.getName() << endl <<
"Race: " << Hero_1.getRace() << endl <<
"Weight:" << Hero_1.getWeight() << endl;

cout << endl;

cout << "Enter your Hero's Name:";
cin >> name;
cout << "Enter your Race (1:Elf 2:Human 3 Dwarf)";
cin >> race;
cout <<"Enter your Hero's weight (in pounds)";
cin >> weight;

HeroProfile Hero_2(name, race, weight);

Hero_2.setName(name);
Hero_2.setRace(race);
Hero_2.setWeight(weight);

cout << endl << "Hero's Name: " << Hero_2.getName() << endl <<
"Race: " << Hero_2.getRace() << endl << "Weight: " << Hero_2.getWeight() <<     endl;

return 0;
}

Файл заголовка

#include <iostream>
#include <string>

using namespace std;

#ifndef HeroProfiel_H
#define HeroProfile_H

class HeroProfile
{

public:
//default constructor
HeroProfile();

//overlaod constructor
HeroProfile(string, int, double);

//destructor
~HeroProfile();

//Accesor functions
string getName() const;
// get name - returns name of patient

int getRace() const;
// getHeight-returns height of patient

double getWeight() const;
// getWeight- returns weight of patient

//Mutator Functions
void setName(string);
//set name of patient
//@param string - name of patient

void setRace(int);
//setHeight-sets heigh tof patient
//@param int- height iof patient

void setWeight(double);
//setWeight-sets weight of patiend
//@param double-weight of patientprivate:
//Memeber variables
string newName;
int newRace;
double newWeight;};

#endif

и второй файл .cpp

#include "HeroProfile.h"
eroProfile::HeroProfile() //Default constructor
{
newRace = 0;
newWeight = 0.0;
}

HeroProfile::HeroProfile(string name, int race, double weight) //Overloaded Constructor
{
newName = name;
newRace = race;
newWeight = weight;
}

HeroProfile::HeroProfile()
}
}

//Accessors
string HeroProfile::getName() const
{
return newName;
}

int HeroProfile::getRace() const
{
return newRace;
}

double HeroProfile::getWeight() const
{
return newWeight;
}

//Mutators
void HeroProfile::setName(string name)
{
newName = name;
}

void HeroProfile::setRace(int race)
{
newRace = race;
}void HeroProfile::setWeight(double weight)
{
newWeight = weight;
}

0

Решение

Как уже отмечали другие, у вас есть 2 определения во втором файле cpp для HeroProfile конструктор по умолчанию HeroProfile::HeroProfile():

Первый

HeroProfile::HeroProfile() //Default constructor
{
newRace = 0;
newWeight = 0.0;
}

а второй

HeroProfile::HeroProfile()
}
}

Исходя из того факта, что я его не вижу, вы, вероятно, намеревались, чтобы второй был деструктором вашего класса (как объявлено в вашем заголовочном файле, но не определено в вашем файле cpp), и в этом случае вы должны заменить его следующим:

HeroProfile::~HeroProfile()
}
}

Надеюсь, вас не смутило то, что HeroProfile::HeroProfile(void) а также HeroProfile::HeroProfile() это то же самое, поэтому я подумал, что должен указать на это.

1

Другие решения

Сообщение означает именно то, что оно говорит. Игнорируя опечатки, первое и третье определения в вашем втором .cpp для той же функции.

1

Перейти к контенту

Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «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

kbx's user avatar

1

У вас неверное понимание, что должно находиться в заголовочном файле, а что — в .cpp.

В заголовочном файле располагайте объявления, а определения — в cpp-файле. В заголовочном файле располагаются также inline-реализации, шаблоны и т.п. вещи, но в вашем случае все, что следует разместить в func.h — это

void Interface();

Все остальное — в .cpp-файлах, и не включать .cpp-файлы с помощью директивы #include — иначе вы получаете нарушение правила одного определения.

ответ дан 1 янв 2018 в 19:50

Harry's user avatar

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

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.

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Вопрос:

Я не мог понять, что мне нужно сделать, чтобы исправить эту ошибку или найти что-либо на этом веб-сайте. В основном я получаю ошибку 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.

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка клапана егр дэу нексия
  • Ошибка контрольной суммы crc при установке nvidia
  • Ошибка компилятора c2079
  • Ошибка кислородный датчик банк 1
  • Ошибка контрольной суммы конфигурации

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: